我剛剛接觸到了controllerAs的angular語法,並試圖瞭解它如何與指令一起工作。我創建了一個用於密碼驗證的指令。我想根據條件使標記爲真,並且這些標記將用於父模板中以顯示錯誤消息。我沒有得到我該如何實現這一點!
VIEW
<div ng-app="myapp">
<fieldset ng-controller="PersonCtrl as person">
<input name="emailID" type="text" ng-model="person.first" >
<input name="pass" type="password" ng-model="person.pass" password-validator>
<p ng-show="person.showMsg">Password validation message here.</p>
</fieldset>
</div>
指令
myapp.directive('passwordValidator',function() {
return {
controller : PasswordCtrl,
controllerAs : 'dvm',
bindToController : true,
require : ['ngModel','passwordValidator'],
link : function(scope,ele,attrs,ctrls) {
var person = ctrls[1];
var ngModelCtrl = ctrls[0];
scope.$watch(function() {
return ngModelCtrl.$modelValue;
},function(newVal) {
if(newVal!='') {
person.showMsg = true;
} else {
person.showMsg = false;
}
console.log(person.showMsg);
});
}
}
function PasswordCtrl() {
}
});
特別我想知道爲什麼,以及如何下方手錶做工精細!
// Why this below is also working, can anyone explain what's going behind!!
scope.$watch('person.pass',function(newVal) {
console.log("Watch fires");
});
這僅僅是學習的目的,所以請解釋如何controllerAs
和bindToController
作品!
你的要求是什麼?解釋或解決方案 –
解決方案詳細說明它的工作原理。 –
在angularjs中使用指令時(或者只是使用angularjs),它對於理解摘要生命週期很重要,它基本上是對作用域模型和視圖之間的變化進行髒檢查。這是使我們的生活更容易的核心功能。這是我讀過的關於該主題的最好的文章https://www.sitepoint.com/understanding-angulars-apply-digest/ –