Với Knockout, tôi có thể nóiLàm cách nào để AngularJS chạy lại chức năng mỗi khi dữ liệu sử dụng thay đổi?
<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>
và result
sẽ được tính toán lại mỗi khi một sự thay đổi và b. Làm thế nào tôi có thể nhận được AngularJS để làm điều này cho tôi? Tôi đã cố gắng
<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>
Sau một chút đọc nhiều hơn, tôi thấy 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>
Nhưng điều đó đòi hỏi tôi phải theo dõi thực tế rằng việc thay đổi a
hoặc b
thay đổi result()
, là có cách nào tự động phát hiện điều này?
bạn đã thử $ xem? http://docs.angularjs.org/api/ng.$rootScope.Scope – Eduardo