1

我试图在数据模型发生变化时立即进行角度刷新。我有数据存储对象是一个相当复杂的模型,但最终应该提供必须渲染到屏幕的数据的角度。我无法弄清楚的是如何通知角度,事情是不同的。通知变化的角度

我想我还没有完全理解我应该如何使用$ scope,但我不能让我的生活得到正确的工作。如果这是一个微不足道的问题,我很抱歉。

<html ng-app="testApp"> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
     <script> 
      function Store() { 
       this.data = [{ msg: "a" }, { msg: "b" }]; 

       this.performWeirdModifications = function() { 
        data.push({ msg: "c" }); 
        data.push({ msg: "d" }); 
       } 
      } 

      var store = new Store(); 

      angular.module('testApp', []).controller('DataController', function() { 
       this.data = store.data; 
      });    
     </script> 
    </head> 
    <body ng-controller="DataController as dataCtrl"> 
     <button onclick="store.performWeirdModifications()">Simulate something</button> 
     <div ng-repeat="data in dataCtrl.data">{{data.msg}}</div> 
    </body> 
</html> 
+0

,而你可以使用$范围。$适用于解决问题,什么我没有得到的,你为什么不使用存储作为服务......这是更加棱角分明的方式... – harishr 2014-10-09 12:22:26

+0

问题是这里的商店实际上是判断一堆遗留代码的东西,这些代码有很多东西。否则,你会从头开始将它构建成角度。 – 2014-10-09 13:07:16

回答

2

将其添加到$scope

angular.module('testApp', []).controller('DataController', function ($scope) { 
     $scope.data = store.data; 
    }); 

以下是我将如何使用服务完成它。

<html ng-app="testApp"> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
     <script> 

      angular.module('testApp', []) 
      .service('Store', function() { 
       this.data = [{ msg: "a" }, { msg: "b" }]; 

       this.performWeirdModifications = function() { 
        this.data.push({ msg: "c" }); 
        this.data.push({ msg: "d" }); 
       }; 
       return this; 
      }) 
      .controller('DataController', function ($scope, Store) { 
       $scope.data = Store.data; 
       $scope.getData = function() { 
        Store.performWeirdModifications(); 
        $scope.data = Store.data; 
       }; 
      });    
     </script> 
    </head> 
    <body ng-controller="DataController as dataCtrl"> 
     <button ng-click="getData()">Simulate something</button> 
     <div ng-repeat="d in data">{{d.msg}}</div> 
    </body> 
</html> 
+0

啊,就是我在找的东西。非常感谢! – 2014-10-09 13:09:43