我正面临AngularJS的新问题。事实上,由于我需要一个“共享”变量,在2个控制器中可读和可更新,我想到在两个控制器中注入工厂的情况下这样做。数据通过http请求加载,但一旦请求完成,var就不会更新。这是我的代码:
//Common factory
app.factory('CurrentGallery',['$q','$http',function($q,$http){
var data = null;
//HTTP request to API
var loadImages = function(query){
$http.post("https://mywebsite.com/api/?"+query).then(function(result){
update(result.data);
});
}
//Update the data var
var update = function(data){
data = data;
console.log("Update called", data);
}
return {
loadImages: loadImages,
update: update,
data: data
}
}]);
//The controller
app.controller("PhotoBestController", ['$scope', 'CurrentGallery', function ($scope,CurrentGallery) {
//$scope.pics is basically the variable I want to update inside my controller
$scope.pics = CurrentGallery.data;
//Send the data of the query for the API
CurrentGallery.loadImages("userInfo=true&exifInfo=true&order=tot_like,DESC");
$scope.$watch(CurrentGallery, function(){
console.log("CurrentGallery has changed");
});
}]);
这是我在控制台中获得的日志:
所以看起来CurrentGallery第一次得到更新,当它为null时,但是,即使它在工厂内部得到更新,它也不会更新$ scope.pics var。
有什么建议?
UPDATE 我遵循了这个帖子中的代码逻辑:AngularJS : How to watch service variables?
app.factory('CurrentGallery',['$q','$http',function($q,$http) {
var updateCallbacks = [];
var data = null;
var loadImages = function(query) {
$http.post("https://mywebsite.com/api/?"+query).then(function(result) {
angular.forEach(updateCallbacks, function(callback) {
callback(result.data);
});
});
}
var registerUpdateCallback(callback) {
updateCallbacks.push(callback);
}
return {
loadImages: loadImages,
registerUpdateCallback: registerUpdateCallback
}
}]);
app.controller("PhotoBestController", ['$scope', 'CurrentGallery', function($scope,CurrentGallery) {
CurrentGallery.registerUpdateCallback(function(data) {
console.log("updated")
});
CurrentGallery.loadImages("userInfo=true&exifInfo=true&order=tot_like,DESC");
}]);
我认为您的数据仅在工厂更新。因此,要在控制器中更新它,您必须从工厂再次获取它。
因此,在监视器中放置监视器的位置会重新分配范围变量:
$scope.$watch(CurrentGallery, function(){
$scope.pics = CurrentGallery.data;
console.log("CurrentGallery has changed");
});