有了淘汰赛,我可以说
<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>
但这需要我跟踪 changea
或b
changes的事实result()
,是否有任何自动检测方法?