这是我的代码。
sampleApp.factory('ProductService', ['$http', '$q', function ($http, $q){
var req = {
method: 'POST',
url: 'ProductData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
var ProductService = {};
ProductService.Products = [];
return {
GetProducts: function () {
var defer = $q.defer();
$http(req).then(function(response) {
ProductService.Products = response.data;
defer.resolve(ProductService.Products);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
},
UpdateInfo: function (ProductID, VariantID) {
for (i in ProductService.Products) {
if (ProductService.Products[i].ProductID == ProductID) {
for (j in ProductService.Products[i].Variants) {
if (ProductService.Products[i].Variants[j].VariantID == VariantID) {
ProductService.Products[i].Variants[j].InCart = 1; /* Updating Info Here, But its not reflecting */
alert ('information updated'); // reaching here
break;
}
}
break;
}
}
}
};
}]);
sampleApp.controller('ProductsController', function ($scope, $routeParams, ProductService, ShoppingCartService) {
$scope.Products = [];
$scope.GetProducts = function() {
ProductService.GetProducts().then
(
function(response) {
$scope.Products = response;
},
function(error) {
alert ('error worng');
}
);
};
$scope.GetProducts();
$scope.$watch('ProductService.Products', function(newVal) {
alert ('hitting watch'); // Not Reaching Here
$scope.Products = NewVal;
alert ($scope.Products);
});
});
我在其他服务中调用ProductService中的UpdateInfo。虽然它达到警觉('信息更新');在UpdateInfo中。但没有达到警觉('击中手表');在控制器中。
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
您的监视表示“ProductService.Products”,并在控制器的范围内进行评估。但是此表达式始终将被评估为undefined
,因为控制器作用域没有ProductService
属性。
请注意,如果你做了
$scope.ProductService = ProductService
它不会有太大变化。实际上,表达式仍然是未定义的,因为ProductService
没有任何名为Products
的属性。唯一属性是GetProducts
和UpdateInfo
,类型为函数。
答案 1 :(得分:2)
不是在观看ProductsService.Products,而是在Scope中维护它的单独副本,为什么不自己使用相同的值。
指定范围内服务的引用。
$scope.ProductService = ProductService;
通过这种方式,您现在将ProductService暴露给视图。现在,在HTML页面中,您可以直接访问ProductServices.Products,一旦服务中的值发生变化,它们就会自动反映在View中。
没有脏$ Watch,没有单独的副本。
编辑:按照@ JB的回答,你必须将一个名为Products的属性添加到服务中。
像这样的东西
return {
Products : [],
GetProducts: function () {
var defer = $q.defer();
$http(req).then(function(response) {
ProductService.Products = response.data;
defer.resolve(ProductService.Products);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
},
........