每次使用的数据发生变化时,如何让AngularJS重新运行一个函数?

时间:2012-08-08 18:23:59

标签: angularjs

使用Knockout,我可以说

<html>
    <head>
        <script type="text/javascript" src="knockout-2.1.0.js"></script>
    </head>
    <body>
        <input type="text" data-bind="value: a"></input> +
        <input type="text" data-bind="value: b"></input> =
        <span data-bind="text: result"></span>
        <script type="text/javascript">
            function ExampleViewModel() {
                this.a = ko.observable(5);
                this.b = ko.observable(6);
                this.result = ko.computed(function() {
                    return parseInt(this.a()) + parseInt(this.b());
                }, this);
            }

            ko.applyBindings(new ExampleViewModel());
        </script>
    </body>
</html>
每次a和b更改时,都会重新计算

result。我怎样才能让AngularJS为我做这个?我试过了

<html ng-app>
    <head>
        <script type="text/javascript" src="angular-1.0.1.min.js"></script>
        <script type="text/javascript">
            function ExampleCtrl($scope) {
                $scope.a = 5;
                $scope.b = 6;
                $scope.result = function() {
                    return this.a + this.b
                };
            }

</script>
    </head>
    <body ng-controller="ExampleCtrl">
        <input type="text" value="{{ a }}"></input> +
        <input type="text" value="{{ b }}"></input> =
        {{ result() }}
    </body>
</html>

经过多一点阅读后,我找到了ng-change

<html ng-app>
    <head>
        <script type="text/javascript" src="angular-1.0.1.min.js"></script>
        <script type="text/javascript">
            function ExampleCtrl($scope) {
                $scope.a = 5;
                $scope.b = 6;
                $scope.result = function() {
                    return parseInt($scope.a) + parseInt($scope.b)
                };
            }

</script>
    </head>
    <body ng-controller="ExampleCtrl">
        <input type="text" ng-model="a" ng-change="result()"></input> +
        <input type="text" ng-model="b" ng-change="result()"></input> =
        {{ result() }}
    </body>
</html>

但是,这需要我跟踪更改ab更改result()的事实,是否有任何自动检测方法?

1 个答案:

答案 0 :(得分:7)

当输入中的ng-model绑定时,只要模型发生变化,您的result()函数就会重新评估:

<input type="text" ng-model="a"></input>

而不是:

<input type="text" value="{{ a }}"></input>