Search code examples
angularjsangularjs-service

Propagating change of data in service to controller


I have a service for storing some application common data. This service can also modify this data and react to events. However I am having trouble with propagating the changes to controllers that are using this service.

I've seen this question and this question, but the solutions don't work for me.

I created a plunker that shows what is my core problem. There is a service object storing common data in sharedObject. It has a function updateObject, which can update the data (in my real app it sends a request to a server). The service is used by main controller. However, when updateObject is called in the service, data are not updated in the controller.

Why is that? Also is this a best practice or am I doing somethign wrong?

Here's the code:

app = angular.module('app', []);

app.factory('object', ['$timeout', function($timeout){
  var sharedObject = {attr1: '', attr2: ''};
  var updateObject = function() {
    $timeout(function(){
      sharedObject = {attr1: 'new value', attr2: 'update value'};
      console.log('updated');
    }, 1000);
  }
  updateObject();
  return sharedObject;
}]);

app.controller('main', [
  '$scope', 'object', function($scope, object) {
    $scope.$watch(function(){return object}, function(obj){
      console.log(obj);
      $scope.object1 = obj;
      }, true);
  }
]);

Solution

  • The problem is that the timeout callback doesn't update the object you're watching. It replaces it by another object. So the watcher still sees the old object, unmodified.

    Replace the code, as in this updated plunker, by

    sharedObject.attr1 ='new value';
    sharedObject.attr2 = 'update value';
    

    and you'll see the values change in the page.