指令只允许在视图和模型值中使用字母字符 [英] Directive to allow only alphabetic characters in view and model value
问题描述
我正在尝试实现一个指令,该指令仅用于将字母输入到文本框中,即从 a-z 或 A-z我确实尝试这样做,
I am trying to achieve a directive that would be used to accept only alphabets into the text box i.e from a-z or A-z I did try to do this by,
angular.module('myApp', []).directive('alphabetsOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/^[a-zA-Z]+$/, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
function MyCtrl($scope) {
$scope.name = ''
}
但这不起作用.
尝试模式
'/^[a-zA-Z]$/'
但没有成功.谁能帮我解决这个问题.
but no success. Can anyone help me with this.
推荐答案
您只需要移动括号内的插入符号 ^
即可否定字母,而其他所有内容都将被替换.[^a-zA-Z]
.您也不需要末尾的 $
.
You just need to move the caret ^
inside the brackets to negate letters, leaving everything else to be replaced. [^a-zA-Z]
. You don't need the $
on the end either.
以下是如何制作更可重用的指令的示例.您可以将其用于各种用途.
Here's an example of how to make a more reusable directive. You could use this for all kinds of things.
<input replace="[^a-zA-Z]" with="" ng-model="name">
.directive('replace', function() {
return {
require: 'ngModel',
scope: {
regex: '@replace',
with: '@with'
},
link: function(scope, element, attrs, model) {
model.$parsers.push(function(val) {
if (!val) { return; }
var regex = new RegExp(scope.regex);
var replaced = val.replace(regex, scope.with);
if (replaced !== val) {
model.$setViewValue(replaced);
model.$render();
}
return replaced;
});
}
};
})
如果你想使用这个 replace
指令,但经常使用一个特定的公式,你可以通过创建另一个使用这个指令的指令来保持代码干燥:
If you wanted to use this replace
directive, but used a particular formula often, you could keep your code DRY by making another directive that uses this one:
<input letters-only ng-model="name">
.directive('lettersOnly', function() {
return {
replace: true,
template: '<input replace="[^a-zA-Z]" with="">'
};
})
这篇关于指令只允许在视图和模型值中使用字母字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!