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>

aとresultbが変更されるたびに再計算されます。どうすれば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>

aしかし、それは私が変化またはb変化するという事実を追跡することを私に要求しますresult()、これを検出する自動の方法はありますか?

4

1 に答える 1

8

次のように入力でng -modelresult()を介してバインドするときにモデルが変更されるたびに、関数が再評価さ れます。

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

それ以外の:

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