AngularJS 带有输入元素的自定义指令,从外部传递验证器
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>
我正在对整个应用程序中出现的修改后的输入字段使用简单的自定义指令:
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>