如何创建自定义输入类型?

Jam*_*sOR 16 javascript angularjs angularjs-directive

我想创建一个类似于AngularJS实现"email"的方式的自定义输入类型.

<input type="email" ng-model="user.email" />
Run Code Online (Sandbox Code Playgroud)

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

<input type="path" ng-model="page.path" />
Run Code Online (Sandbox Code Playgroud)

关于如何实现这一点的任何想法?到目前为止,我只能弄清楚如何实现自定义指令,其中'path'是标记,属性或类的名称.

例如,我可以让它工作,但它与其他表单字段不一致,我真的希望它们看起来一样.

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

Mar*_*tin 18

如果type属性设置为"path",则可以通过使用自定义逻辑创建输入指令来创建自己的input type ="path".

我创建了一个简单的例子,简单地替换\/.该指令如下所示:

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);
            });
          });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

Example

更新:已更改on,offbind,unbind删除jQuery的依赖.示例已更新.