[英]AngularJS custom directive with input element, pass validator from outside
我在我的應用程序中使用一個簡單的自定義指令來修改輸入字段:
app.directive('editor', function() {
return {
restrict: 'E',
templateUrl: 'editor.html',
scope: { value: '=' }
};
});
editor.html
基本上創建了一個帶有附加控件的input
元素。 簡化它看起來像這樣:
<div>
<input ng-model="value">
<!-- more code here -->
</div>
我使用<editor value="{{object.name}}"></editor>
訪問我的指令。 這很完美。 現在我需要對輸入執行不同的驗證。 使用的必要驗證器各不相同,所以我希望能夠將實際的驗證器傳遞給我的指令。 就像是:
<editor value="{{object.name}}" validator-a validator-b></editor>
要么
<editor value="{{object.name}}" validators="validatorA,validatorB"></editor>
我怎么能實現這一目標?
您正在創建自定義輸入控件,因此您可能也支持ng-model
- 這是正確的做法。
並且,驗證器 - 內置和自定義 - 僅require: "ngModel"
用於其功能,並且它們與底層DOM實現獨立(通過設計),因此使用ng-model
自動支持所有基於ng-model
的驗證器。
擁有ng-model
支持也將使您的指令參與form
驗證。
由於你在模板中使用了一個現有的指令(即<input>
),你甚至不需要打擾DOM,就像你從頭開始構建一些東西一樣。
app.directive("editor", function(){
return {
require: "?ngModel",
scope: true,
template: "<input ng-model='value' ng-change='onChange()'>",
link: function(scope, element, attrs, ngModel){
if (!ngModel) return;
scope.onChange = function(){
ngModel.$setViewValue(scope.value);
};
ngModel.$render = function(){
scope.value = ngModel.$modelValue;
};
}
};
});
然后您可以直接應用驗證器:
<editor ng-model="foo" minlength="3"></editor>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.