使用 controller as
语法时如何订阅属性更改?
controller('TestCtrl', function ($scope) {
this.name = 'Max';
this.changeName = function () {
this.name = new Date();
}
// not working
$scope.$watch("name",function(value){
console.log(value)
});
});
<div ng-controller="TestCtrl as test">
<input type="text" ng-model="test.name" />
<a ng-click="test.changeName()" href="#">Change Name</a>
</div>
最佳答案
只需绑定(bind)相关上下文即可。
$scope.$watch(angular.bind(this, function () {
return this.name;
}), function (newVal) {
console.log('Name changed to ' + newVal);
});
示例:http://jsbin.com/yinadoce/1/edit
更新:
Bogdan Gersak 的答案实际上是等价的,两个答案都尝试将 this
与正确的上下文绑定(bind)。但是,我发现他的答案更清晰。
话虽如此,首先,您必须了解the underlying idea behind it .
更新 2:
对于那些使用 ES6 的人,通过使用 箭头函数
,您可以获得具有正确上下文 OOTB 的函数。
$scope.$watch(() => this.name, function (newVal) {
console.log('Name changed to ' + newVal);
});
关于javascript - Angularjs: 'controller as syntax' 和 $watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24078535/