javascriptangularjsangularjs-scopeangularjs-controllerangularjs-factory

AngularJS - Factory variable doesn't update in controller


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:

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?


Solution

  • UPDATE
    I followed the code logic in this thread: 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");
    }]);