У меня возникла проблема с AngularJS. Infact, так как мне нужно иметь «общую» переменную, читаемую и обновляемую в двух контроллерах, я думал об этом с фабрикой, введенной в обоих контроллерах. Данные загружаются через HTTP-запрос, но как только запрос завершен, var просто не обновляется. Вот мой код:AngularJS - Заводская переменная не обновляется в контроллере
//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 изменил
- Update называется, Object {...}
Так это кажется, что CurrentGallery обновляется в первый раз, когда он равен нулю, но затем, даже если он обновляется внутри фабрики, он не обновляет переменную $ scope.pics var.
Любые предложения?
это может помочь вам http://stackoverflow.com/questions/30596258/watch-factory-variable- с угловым –
@VinodLouis, похоже, это не проблема! Он дает точно такой же результат, поэтому ничего не обновляется – Wendigo