這是我的代碼。即使在服務變量中進行更改後,AngularJS手錶仍未打入控制器
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中。但沒有達到警戒狀態('打手錶');在控制器中。
有人能幫我解決這個問題嗎?
感謝您的答覆。我非常感謝你在範圍內分配對該服務的引用。 $ scope.ProductService = ProductService;但在這種情況下,如何以及在哪裏調用服務函數「GetProducts」從數據庫中獲取數據。 – 2015-04-04 07:19:47
你可以在任何地方打電話。只要你的服務變量得到修改,你就會在視圖中反映出這些變化。一切都將保持不變,除了範圍內不會有任何產品副本,您將使用服務參考直接訪問它們。 – 2015-04-04 08:08:50
我在我的代碼中使用routeProvider。問題是當我移動到產品模板時,ProductController進入畫面。 $ scope.GetProducts();將在那裏調用,產品將從DB填充。現在一些服務做出了將反映的變化。現在,當我移動到一些其他模板,然後再次產品模板,然後再次$ scope.GetProducts();將被調用。我的最新更新產品將消失.. – 2015-04-04 08:20:31