服务内部的数据更改不会更新范围

Data change inside Service does not update the Scope

我将我的数据存储在 Angular 服务中(以在控制器之间共享)并提供更新它的功能:

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

  return {
    json: _json,

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

})

然后我简单地将数据拉入控制器:

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

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

问题是 - 当调用 MC.changeTo 函数时,它会更新服务内部的 _json 变量,但不会更新控制器中的变量!

这里JSbin说明了这个问题。

知道我做错了什么吗?

试试这个。您的代码不起作用,因为 _json 变量每次都引用不同的对象。 angular.copy 将新对象复制到同一引用。

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