[英]How to create a custom input type?
我想创建一个类似于AngularJS实现“email”的方式的自定义输入类型。
<input type="email" ng-model="user.email" />
我想创建的是这样的输入类型:
<input type="path" ng-model="page.path" />
关于如何实现这一点的任何想法? 到目前为止,我只能弄清楚如何实现自定义指令,其中'path'是标记,属性或类的名称。
例如,我可以让它工作,但它与其他表单字段不一致 ,我真的希望它们看起来一样。
<input type="text" ng-model="page.path" path />
app.directive('path', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) { ... }
};
});
如果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);
});
});
}
};
});
更新 :改变on
, off
到bind
, unbind
删除jQuery的依赖。 示例已更新。
通过使用ngModelController的$parsers
属性可以实现替代解决方案。 此属性表示一系列解析器,在将它们传递给验证之前应用于输入组件的值(并最终将它们分配给模型)。 有了这个,解决方案可以写成:
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
,它是$formatters
的管道,可将模型值转换为输入中显示的值。
请看这里的plunker。
考虑编译函数是第一个在线,它会不会更好:
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);
});
});
}
}
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.