У меня возникла новая проблема с 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 обновляется в самый первый раз, когда он равен нулю, но затем, даже если он обновляется внутри фабрики, он не обновляет переменную $scope.pics.
Какие-либо предложения?