有了Knockout,我可以说
<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>
Run Code Online (Sandbox Code Playgroud)
并且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>
Run Code Online (Sandbox Code Playgroud)
经过一番阅读,我发现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>
Run Code Online (Sandbox Code Playgroud)
但这需要我跟踪变化a或b变化的事实result(),是否有任何自动检测方法?
result()当您在输入中通过ng-model进行绑定时,只要模型发生更改,您的函数就会重新评估 ,如下所示:
<input type="text" ng-model="a"></input>
Run Code Online (Sandbox Code Playgroud)
代替:
<input type="text" value="{{ a }}"></input>
Run Code Online (Sandbox Code Playgroud)