0
votes

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?

1
what is your desire out put ?Shailendra Sharma
@ShailendraSharma To have a scalable data storage architecture and avoid storing in the controllers.Dmitri Zaitsev
can you please put it into plunker, jsbin is disabled at my workbaklazan
You basically have MC.json = object1 -> changeTo(object2) -> _json = object2.a better oliver

1 Answers

1
votes

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);
        }