I'm facing a new issue with AngularJS. Infact, since I need to have a "shared" variable, readable and updatable in 2 controllers, I thought about doing that with a factory injected in both the controllers. The data are loaded via http request, but once the request is completed, the var just doesn't update. Here's my code:
//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");
});
}]);
This is the log I get in my console:
- CurrentGallery has changed
- Update called, Object{...}
So it seems the CurrentGallery get updated the very first time, when it's null, but then, even if it gets updated inside the factory, it doens't update the $scope.pics var.
Any suggestions?