AngularJS。将$ watch添加到特定型号
问题描述:
我是angularJS新手,我不知道如何将$watch
添加到特定型号。在通过angularjs教程时,我遇到了一些问题。我在评论部分提到了我的疑问。请通过这个。
(function(angular) {
angular.module('controllerAsExample', [])
.controller('SettingsController1', SettingsController1);
function SettingsController1() {
this.name = "John Smith";
this.contacts = [
{type: 'phone', value: '408 555 1212'},
{type: 'email', value: '[email protected]'} ];
}
//how to add $watch to ng-model 'settings.name'
/*$scope.$watch("settings.name", function(oldval, newval){
console.log(oldval + " + " + newval);
});*/
SettingsController1.prototype.greet = function() {
console.log(this.name);
};
})(window.angular);
HTML代码..
<body ng-app="controllerAsExample">
<div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
<label>Name: <input type="text" ng-model="settings.name"/></label>
<button ng-click="settings.greet()">greet</button><br/>
</div>
</body>
这里查看我的link
答
除非是在你的代码中的一些其他功能你是不是表明,你不需要$表()。
$ watch()是angularJS最受滥用的函数之一。许多不熟悉AngularJS的开发人员都会添加不必要的$ watch()表达式,这会使代码复杂化。
带$ watch()的控制器通常是一种糟糕的代码异味。肯定有你应该使用$ watch的地方 - 但从你的例子来说,这不是其中的一个。
相反,您可以执行以下操作。
(function(angular) {
angular.module('controllerAsExample', [])
.controller('SettingsController1', SettingsController1);
function SettingsController1() {
this.name = "John Smith";
this.contacts = [
{type: 'phone', value: '408 555 1212'},
{type: 'email', value: '[email protected]'} ];
}
SettingsController1.prototype.greet = function() {
console.log(this.name);
};
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="controllerAsExample">
<div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
<label>Name: <input type="text" ng-model="settings.name"/></label>
<button ng-click="settings.greet()">greet</button><br/>
</div>
</div>
答
基本上,你需要注入$scope
上下文。如SO answer所述。
function SettingsController1($scope) {
this.name = "John Smith";
this.contacts = [
{type: 'phone', value: '408 555 1212'},
{type: 'email', value: '[email protected]'} ];
$scope.$watch(angular.bind(this, function() {
return this.name;
}), function (newVal, oldVal) {
console.log('Name changed to ' + newVal + ', old value = ' + oldVal);
});
}
通知的$scope
被传递给功能控制器,然后angular.bind(this
它告诉监视器正确的上下文。
为什么要添加$看? – Ajay