2012-08-08 4 views
6

Con Knockout, posso direCome posso fare in modo che AngularJS riesegua una funzione ogni volta che i dati che usa cambiano?

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

e result sarà ricalcolato ogni volta che un cambiamento e b. Come posso convincere AngularJS a fare questo per me? Ho provato

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

Dopo un po 'di più la lettura, ho trovato 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> 

Ma che mi obbliga a tenere traccia del fatto che cambiare a o b cambia result(), c'è qualche modo automatico di scoprire questo?

+0

Hai provato $ guardare? http://docs.angularjs.org/api/ng.$rootScope.Scope – Eduardo

risposta

7

La funzione result() saranno rivalutati ogni volta che il modello cambia quando vincolante via ng-model nei vostri input in questo modo:

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

invece di:

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

Sembra che solo utilizzando ng-modello funziona (non ho bisogno di specificare ng-cambio), grazie. Purtroppo, si aggiorna all'istante. C'è un modo per aggiornarlo solo quando l'attenzione lascia l'input? –

+0

Questo post può aiutare con rimandando al modello cambia quando il focus lascia l'ingresso: http://stackoverflow.com/a/11870341/1207991 – Gloopy