2012-08-08 1 views
6

、私はAngularJSは、使用するデータが変更されるたびに関数を再実行する方法を教えてください。ノックアウトで

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

しかし、それはaまたはbを変更するとresult()を変更しているという事実を追跡するために私を必要とし、任意の自動的な方法がありますこれを検出するの?

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

の代わり:あなたの入力にng-modelを経由して結合する際のモデルは次のように変更するたびに

+0

あなたは$観を試みたことがありますか? http://docs.angularjs.org/api/ng.$ro​​otScope.Scope – Eduardo

答えて

7

あなたresult()関数が再評価されます

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

ng-modelの作品を使用しているようです(ng-changeを指定する必要はありません)。ありがとうございます。残念ながら、即座に更新されます。フォーカスが入力を離れると、それを更新するだけの方法はありますか? –

+0

この投稿は、モデルの変更をフォーカスが入力から離れるまで延期するのに役立ちます。http://stackoverflow.com/a/11870341/1207991 – Gloopy

関連する問題