简体   繁体   English

带有input元素的AngularJS自定义指令,从外部传递验证器

[英]AngularJS custom directive with input element, pass validator from outside

I'm using a simple custom directive for a modified input field which occurs throughout my application: 我在我的应用程序中使用一个简单的自定义指令来修改输入字段:

app.directive('editor', function() {
    return {
        restrict: 'E',
        templateUrl: 'editor.html',
        scope: { value: '=' }
    };
});

The editor.html basically creates an input element with additional controls. editor.html基本上创建了一个带有附加控件的input元素。 Simplified it looks like this: 简化它看起来像这样:

<div>
    <input ng-model="value">
    <!-- more code here -->
</div>

I access my directive using <editor value="{{object.name}}"></editor> . 我使用<editor value="{{object.name}}"></editor>访问我的指令。 This works perfect. 这很完美。 Now I need to perform different validations on the input. 现在我需要对输入执行不同的验证。 The necessary validators to use vary, so I would like to be able to pass the actual validators to my directive. 使用的必要验证器各不相同,所以我希望能够将实际的验证器传递给我的指令。 Something like: 就像是:

<editor value="{{object.name}}" validator-a validator-b></editor>

or 要么

<editor value="{{object.name}}" validators="validatorA,validatorB"></editor>

How could I achieve that? 我怎么能实现这一目标?

You are creating a custom input control, so you might as well support ng-model - which is the right thing to do. 您正在创建自定义输入控件,因此您可能也支持ng-model - 这是正确的做法。

And, validators - built-in and custom - only require: "ngModel" for their function and they are independent (by design) from the underlying DOM implementation, so having ng-model automatically supports all ng-model -based validators. 并且,验证器 - 内置和自定义 - 仅require: "ngModel"用于其功能,并且它们与底层DOM实现独立(通过设计),因此使用ng-model自动支持所有基于ng-model的验证器。

Having ng-model support will also make your directive participate in form validation. 拥有ng-model支持也将使您的指令参与form验证。

Since you are using an existing directive inside the template (ie <input> ), you don't even need to bother with DOM, as you would've had you built something from scratch. 由于你在模板中使用了一个现有的指令(即<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;
      };
    }
  };
});

Then you can just apply validators directly: 然后您可以直接应用验证器:

<editor ng-model="foo" minlength="3"></editor>

http://plnkr.co/edit/k21Oem6kT8SXUefyhbI6?p=preview http://plnkr.co/edit/k21Oem6kT8SXUefyhbI6?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM