目前,我正在使用Controller As格式来确定控制器的作用域。
这对于保持视图上的值范围清晰和易于理解非常有用。
<div ng-app="myApp" ng-controller="myController as myctrl">
<ul>
<li ng-repeat="contact in myctrl.contacts">
<input type="text" ng-model="contact.name.first" />
</li>
</ul>
</div>然而,在实现$watch时,我遇到了问题,因为它似乎依赖于$scope,因此下面的内容将无法工作。
angular.module('myApp',[])
.controller('myController',['contacts',function(contacts) {
this.contacts = contacts;
this.$watch('contacts', function(newValue, oldValue) {
console.log({older: oldValue, newer:newValue});
});
}]);我得到的未定义不是一个函数,在引用this时,没有方法$watch。
是否有一种方法可以使用$watch格式对值进行Controller As处理?
JS Fiddle
发布于 2014-09-09 15:15:39
即使使用controllerAs格式,$scope也存在。
实际上,controllerAs所做的是将控制器实例的this绑定到$scope。
例如,controller="myController as myctrl"做(幕后):$scope.myctrl = this ( this引用myController实例)。
因此,您只需为手表注入并使用$scope:
.controller('myController', function ($scope, contacts) {
this.contacts = contacts;
$scope.$watch(function () {
return contacts;
}, function (newValue, oldValue) {...});
});发布于 2015-03-02 23:52:44
$scope.$watch("contact", callback, true) // true makes it a deep/recursive watch发布于 2015-07-23 11:00:01
尝尝这个,
$scope.$watch(angular.bind(this, function () {
return this.contacts;
}), function (newValue, oldValue) {
console.log((newValue + ' - ' + oldValue));
});https://stackoverflow.com/questions/25748001
复制相似问题