AngularJS 中的掩码 [英] Masking in AngularJS
本文介绍了AngularJS 中的掩码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在 angularJS 中创建一个看起来像这样的掩码
Is it possible to create a mask in angularJS that looks like this
02 年 07 个月.
02years 07months.
当用户点击文本框时,它应该变成下面的文本
And when the user clicks on the text box it should change to the following text
0207
非常感谢!
推荐答案
您可以使用指令来绑定焦点和模糊事件.http://plnkr.co/sFyfYstSlQpZtLUGbmwh
You can use a directive to bind to focus and blur events. http://plnkr.co/sFyfYstSlQpZtLUGbmwh
<input type="text" year-month data="foo.bar"></input>
app.directive('yearMonth', function() {
return {
restrict: 'A',
scope: {
data: '='
},
link: function(scope, element, attr) {
var re = /(\d{2})(\d{1,2})()/;
function addMask(text) {
return text.replace(re, "$1years$2months");
}
function removeMask(text) {
return text.replace(re, "$1$2");
}
element.val(addMask(scope.data));
element.bind('blur', function () {
scope.$apply(function() {
var text = element.val();
scope.data = text;
element.val(addMask(text));
});
});
element.bind('focus', function () {
scope.$apply(function() {
element.val(removeMask(scope.data));
});
});
}
};
});
但是,请务必阅读此问题:如何在 angular.js 中进行双向过滤? 可能有一个更好的解决方案,即使用 ngModelController
的 parsers
和 formatters
.
But, be sure to read this question: How to do two-way filtering in angular.js? There is likely a preferable solution that users the parsers
and formatters
of ngModelController
.
这篇关于AngularJS 中的掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文