Dmitri Zaitsev
Dmitri Zaitsev

Reputation: 14046

Data change inside Service does not update the Scope

I am storing my data inside Angular service (to share across controllers) and provide a function to update it:

.factory('DataManager', function($rootScope){
  var _json = {init: 'from DataManager'};

  return {
    json: _json,

    changeTo: function (newVal) {
      _json = newVal;      
      console.log("Changing to ", _json);
    }
  };

})

Then I simply pull the data into controller:

.controller('MainCtrl', function(DataManager){
  var MC = this;

  MC.json = DataManager.json;
  MC.changeTo = DataManager.changeTo;
})

The problem is - when MC.changeTo function is called, it does update _json variable inside the Service, but not in the controller!

Here is JSbin illustrating the problem.

Any idea what I am doing wrong here?

Upvotes: 0

Views: 87

Answers (1)

baklazan
baklazan

Reputation: 821

Try this. Your code doesn't work because _json variable is refering to diffrent object each time. angular.copy copies the new object to the same reference.

 changeTo: function (newVal) {
          angular.copy(newVal, _json);      
          console.log("Changing to ", _json);
        }

Upvotes: 1

Related Questions