如何创建自定义输入类型?(How to create a custom input type?)

2019-07-19 10:52发布

我想创建一个类似于AngularJS实现“电子邮件”,例如方式自定义输入类型。

<input type="email" ng-model="user.email" />

我想创建一个输入型是这样的:

<input type="path" ng-model="page.path" />

这是如何的任何想法可以实现? 到目前为止,我只能够想出如何实现自定义的指令,其中“路径”是标签,属性或类的名称。

例如,我能得到这个工作,但它与其他表单字段不一致 ,我真的希望他们看起来是一样的。

<input type="text" ng-model="page.path" path />
app.directive('path', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) { ... }
  };
});

Answer 1:

您可以通过,如果该类型属性设置为“路径”创建自定义逻辑输入指令创建自己的输入型=“路径”。

我创建了一个简单的例子,只是替换\/ 。 该指令是这样的:

module.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
          if (attr.type !== 'path') return;

          // Override the input event and add custom 'path' logic
          element.unbind('input');
          element.bind('input', function () {
            var path = this.value.replace(/\\/g, '/');

            scope.$apply(function () {
              ngModel.$setViewValue(path);
            });
          });
        }
    };
});

更新 :改变onoffbindunbind删除jQuery的依赖。 例如更新。



Answer 2:

另一种解决方案可以通过使用来实现$parsers的财产ngModelController 。 此属性表示将它们传递给验证(并且最终将其分配到模型)之前被施加到输入分量的值解析器的链。 有了这个,该解决方案可以写成:

module.directive('input', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
          if (attr.type !== 'path') return;

          ngModel.$parsers.push(function(v) {
            return v.replace(/\\/g, '/');
          });
        }
    };
});

请注意,没有其他属性$formatters它是变换模型值转换成输入显示的数值格式化的管道。

见这里的plunker。



Answer 3:

考虑到编译功能是排在第一位,岂不是更好:

module.directive('input', function() {
  return {
    restrict: 'E',
    require: 'ngModel',
    compile: function Compile(tElement, tAttrs) {
      if (tAttrs.type !== 'path') return;

      return function PostLink(scope, element, attr, ngModel) {
        // Override the input event and add custom 'path' logic
        element.unbind('input');
        element.bind('input', function () {
          var path = this.value.replace(/\\/g, '/');

          scope.$apply(function () {
            ngModel.$setViewValue(path);
          });
        });
      }
    }
  };
});


文章来源: How to create a custom input type?