6

有了淘汰赛,我可以说

<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>

并且result每次 a 和 b 变化时都会重新计算。我怎样才能让 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>

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

4

1 回答 1

8

每当模型在您的输入中通过ng-model绑定时发生更改时,您的result()函数将被重新评估, 如下所示:

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

代替:

<input type="text" value="{{ a }}"></input>
于 2012-08-08T18:34:59.453 回答