如何创建自定义输入类型? [英] How to create a custom input type?

查看:31
本文介绍了如何创建自定义输入类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a custom input type similar to the way AngularJS implements "email", for example.

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

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

What I would like to create is an input type like this:

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

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

Any ideas on how this can be accomplished? So far, I've only been able to figure out how to implement custom directives where 'path' is the name of the tag, attribute or class.

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

For example, I can get this to work but it is inconsistent with the other form fields and I'd really like them to look the same.

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

app.directive('path', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) { ... }
  };
});

推荐答案

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

You can create your own input type="path" by creating an input directive with custom logic if the type attribute is set to "path".

我创建了一个简单的示例,它只是将 \ 替换为 /.该指令如下所示:

I've created a simple example that simply replaces \ with /. The directive looks like this:

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);
            });
          });
        }
    };
});

示例

更新:将onoff改为bindunbind以移除jQuery 依赖.示例已更新.

Update: Changed on, off to bind, unbind to remove jQuery dependency. Example updated.

这篇关于如何创建自定义输入类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆