隨着淘汰賽,我可以說我怎樣才能讓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()
,有沒有自動的方式檢測到這個?
你試過$看? http://docs.angularjs.org/api/ng.$rootScope.Scope – Eduardo 2012-08-08 18:33:00