如何在使用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>
发布于 2014-08-18 15:13:51
我通常这样做:
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)
});
});
发布于 2014-06-06 17:43:40
发布于 2014-11-25 21:49:59
类似于使用"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)
});
})
通过这种方式,您不需要绑定到DOM中指定的名称("TestCtrl as .bind“),并且还避免了对函数进行测试( this )的需要。
与指定的原始...for一起使用:
<div ng-controller="TestCtrl as test">
<input type="text" ng-model="test.name" />
<a ng-click="test.changeName()" href="#">Change Name</a>
</div>
https://stackoverflow.com/questions/24078535
复制相似问题