我遇到了 AngularJS 的新问题。 事实上,由于我需要有一个“共享”变量,在两个 Controller 中可读且可更新,所以我考虑通过在两个 Controller 中注入(inject)一个工厂来实现这一点。数据是通过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 似乎是第一次更新,当它为空时,但是,即使它在工厂内部更新,它也不会更新 $scope.pics 变量。
有什么建议吗?
最佳答案
更新
我遵循了这个线程中的代码逻辑: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");
}]);
关于javascript - AngularJS - 工厂变量不会在 Controller 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41759851/