我通过服务获取我的视图数据并使用angular.copy()分配给局部变量;
var init = function () {
$scope.product = angular.copy(EditItemFactory.getSelectedItem());
}
View of my UI after calling init function
$scope.UpdateItem = function (data) {
console.log(data);
var Data = DataFactory.UpdateItem(data);
if (parseInt(Data) != 0) {
$modalInstance.dismiss('Close');
} else {
console.log(Data);
}
}
我正在传递更新功能以更新项目并存储在数据库中。
但在DB中更新后,数据正在UI中更新
以下是我的控制器的完整代码:
(function () {
var productEditCtrl = function ($scope, $modalInstance, EditItemFactory, DataFactory) {
$scope.cancel = function () {
$modalInstance.dismiss('Close');
};
$scope.UpdateItem = function (data) {
console.log(data);
var Data = DataFactory.UpdateItem(data);
if (parseInt(Data) != 0) {
$modalInstance.dismiss('Close');
} else {
console.log(Data);
}
}
var init = function () {
$scope.product = angular.copy(EditItemFactory.getSelectedItem());
}
init();
}
productEditCtrl.$inject = ['$scope', '$modalInstance', 'EditItemFactory', 'DataFactory']
angular.module("SplitWise").controller("productEditCtrl", productEditCtrl)())
我无法将更改绑定到UI。
注意:我想在更新的数据存储到数据库后才更新UI
数据工厂代码:
(function(){
var DataFactory = function($http)
{
var factory = {};
factory.getAllItems = function()
{
return $http.get("http://localhost:8080/GetAllItems")
}
factory.DeleteItem = function(Product)
{
$http.post("http://localhost:8080/DeleteItem",{"Model":Product.MODEL_NUMBER}).success(function(data){
return data;
}).error(function(err)
{
return err;
})
}
factory.UpdateItem = function(Product)
{
$http.post("http://localhost:8080/UpdateItem",{"Model":Product.MODEL_NUMBER,"Name":Product.NAME,"MSRP":Product.MSRP,"Quantity":Product.QUANTITY}).success(function(Data){
return Data;
}).error(function(err){
return err;
})
}
return factory
}
DataFactory.$inject=['$http']
angular.module('SplitWise').factory("DataFactory",DataFactory)
}())
答案 0 :(得分:0)
$http.post
是异步的,因此UpdateItem
函数在从服务器接收之前返回Data
,因此它是undefinded
。你想要做的就是等到成功分配,然后用它做点什么。
var DataFactory = function($http) {
// ...
factory.UpdateItem = function(Product)
{
return $http.post("http://localhost:8080/UpdateItem",{"Model":Product.MODEL_NUMBER,"Name":Product.NAME,"MSRP":Product.MSRP,"Quantity":Product.QUANTITY});
}
// ...
}
然后像这样使用UpdateItem
函数:
$scope.UpdateItem = function (data) {
console.log(data);
DataFactory.UpdateItem(data).then(function(resp) {
if (parseInt(resp.data) != 0) {
$modalInstance.dismiss('Close');
} else {
console.log(resp);
}
}, function(err) {
console.log(err);
});
}