2012-08-08 54 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> 

但是,這要求我保持的事實的軌道,改變ab改變result(),有沒有自動的方式檢測到這個?

+0

你試過$看? http://docs.angularjs.org/api/ng.$ro​​otScope.Scope – Eduardo 2012-08-08 18:33:00

回答

7

result()功能將被重新評估每當模型像這樣在你的輸入通過ng-model結合時的變化:中

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

代替:

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

它看起來就像使用ng模型的作品(我不需要指定ng-change),謝謝。不幸的是,它立即更新。有一種方法只在焦點離開輸入時才更新它? – 2012-08-08 18:41:54

+0

這篇文章可能會幫助推遲焦點離開輸入時的模型更改:http://stackoverflow.com/a/11870341/1207991 – Gloopy 2012-08-08 18:44:23

相關問題