Angularjs: 'controller as syntax' 和 $watch [英] Angularjs: 'controller as syntax' and $watch
问题描述
使用controller as
语法时如何订阅属性变化?
controller('TestCtrl', function ($scope) {this.name = '最大';this.changeName = 函数 () {this.name = new Date();}//不工作$scope.$watch("name",function(value){控制台日志(值)});});
<input type="text" ng-model="test.name"/><a ng-click="test.changeName()" href="#">更改名称</a>
只需绑定相关上下文即可.
$scope.$watch(angular.bind(this, function () {返回 this.name;}), 函数 (newVal) {console.log('名称更改为' + newVal);});
示例:http://jsbin.com/yinadoce/1/edit
更新:
Bogdan Gersak 的答案实际上是等价的,两个答案都尝试将 this
与正确的上下文绑定.但是,我发现他的回答更简洁.
话虽如此,首先,您必须了解基本思想后面.
更新 2:
对于那些使用 ES6 的人,通过使用 箭头函数
,您可以获得一个具有正确上下文 OOTB 的函数.
$scope.$watch(() => this.name, function (newVal) {console.log('名称更改为' + newVal);});
How to subscribe on property change when using controller as
syntax?
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>
Just bind the relevant context.
$scope.$watch(angular.bind(this, function () {
return this.name;
}), function (newVal) {
console.log('Name changed to ' + newVal);
});
Example: http://jsbin.com/yinadoce/1/edit
UPDATE:
Bogdan Gersak's answer is actually kind of equivalent, both answers try binding this
with the right context. However, I found his answer cleaner.
Having that said, first and foremost, you have to understand the underlying idea behind it.
UPDATE 2:
For those who use ES6, by using arrow function
you get a function with the right context OOTB.
$scope.$watch(() => this.name, function (newVal) {
console.log('Name changed to ' + newVal);
});
这篇关于Angularjs: 'controller as syntax' 和 $watch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!