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

相关问题