Mir*_*ron 153 javascript angularjs angularjs-scope ng-controller
使用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)
});
});
Run Code Online (Sandbox Code Playgroud)
<div ng-controller="TestCtrl as test">
<input type="text" ng-model="test.name" />
<a ng-click="test.changeName()" href="#">Change Name</a>
</div>
Run Code Online (Sandbox Code Playgroud)
Roy*_*loh 159
只需绑定相关的上下文.
$scope.$watch(angular.bind(this, function () {
return this.name;
}), function (newVal) {
console.log('Name changed to ' + newVal);
});
Run Code Online (Sandbox Code Playgroud)
示例:http://jsbin.com/yinadoce/1/edit
更新:
Bogdan Gersak的回答实际上是等同的,两个答案都尝试this用正确的语境绑定.但是,我发现他的答案更清晰.
说到这一点,首先,你必须了解它背后的基本思想.
更新2:
对于那些使用ES6的人来说,通过使用arrow function你可以得到一个具有正确上下文OOTB的函数.
$scope.$watch(() => this.name, function (newVal) {
console.log('Name changed to ' + newVal);
});
Run Code Online (Sandbox Code Playgroud)
Nic*_*oli 138
我经常这样做:
controller('TestCtrl', function ($scope) {
var self = this;
this.name = 'Max';
this.changeName = function () {
this.name = new Date();
}
$scope.$watch(function () {
return self.name;
},function(value){
console.log(value)
});
});
Run Code Online (Sandbox Code Playgroud)
Art*_*ich 23
您可以使用:
$scope.$watch("test.name",function(value){
console.log(value)
});
Run Code Online (Sandbox Code Playgroud)
这是JSFiddle和你的例子.
小智 13
与使用"TestCtrl as test"中的"test"类似,如另一个答案中所述,您可以为您的范围指定"self":
controller('TestCtrl', function($scope){
var self = this;
$scope.self = self;
self.name = 'max';
self.changeName = function(){
self.name = new Date();
}
$scope.$watch("self.name",function(value){
console.log(value)
});
})
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您不依赖于DOM中指定的名称("TestCtrl as test"),也避免了.bind(this)对函数的需要.
...用于指定的原始html:
<div ng-controller="TestCtrl as test">
<input type="text" ng-model="test.name" />
<a ng-click="test.changeName()" href="#">Change Name</a>
</div>
Run Code Online (Sandbox Code Playgroud)
Nie*_*eek 12
AngularJs 1.5支持ControllerAs结构的默认$ ctrl.
$scope.$watch("$ctrl.name", (value) => {
console.log(value)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51985 次 |
| 最近记录: |