我正在處理幾個組件(指令)以幫助進行表單驗證。我希望組件知道相關輸入元素的狀態(如需要)。例如...直接從form.FormController訪問表單元素?
標記:
<form name="editUser">
<control-label input="editUser.name">Name</control-label>
<input type="text" name="name" ng-model="user.name" required/>
</form>
指令:
app.directive("controlLabel", function() {
return {
restrict: "E",
replace: true,
transclude: true,
scope: {
input: "=input"
},
template:
'<label class="control-label">'+
'<span ng-transclude>{{label}}</span>'+
'<span ng-if="input.required"> (required!)</span>'+ // doesn't work?
'</label>'
};
});
輸出:
<form name="editUser">
<label>
<span>Name</span>
<span>(required!)</span>
</label>
<input type="text" name="name" ng-model="user.name" required/>
</form>
源因爲form.FormController讓我相信這是不可能的。有什麼辦法可以至少訪問元素上的attrs?我想過使用裝飾器,但到目前爲止,我還沒有弄清楚如何完成這件事。
我需要編輯標誌始終顯示,而不僅僅是$ error – Brian
@Brian:然後使用'input。$ validators.required'。更新了上面的答案。 – codef0rmer
謝謝@ codeF0rmer,這正是我正在尋找的。甚至不知道存在$驗證器:P – Brian