通知变化的角度

时间:2014-10-09 12:06:29

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

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

我想我还没有完全理解我应该如何使用$ 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>

1 个答案:

答案 0 :(得分: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>