Hma*_*ish 1 javascript regex angularjs angularjs-directive
我试图实现一个指令,用于只接受字母到文本框中,即从az或Az我尝试这样做,
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 = ''
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用.
试过模式
'/^[a-zA-Z]$/'
Run Code Online (Sandbox Code Playgroud)
但没有成功.谁能帮我这个.
m59*_*m59 17
您只需将插入符号移动到^括号内以取消字母,将其他所有内容都替换掉.[^a-zA-Z].你也不需要那个$.
这是一个如何制作更可重用指令的示例.你可以用它来做各种事情.
<input replace="[^a-zA-Z]" with="" ng-model="name">
Run Code Online (Sandbox Code Playgroud)
.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;
});
}
};
})
Run Code Online (Sandbox Code Playgroud)
如果您想使用此replace指令,但经常使用特定的公式,则可以通过使用另一个使用此指令的指令来保持代码DRY:
<input letters-only ng-model="name">
Run Code Online (Sandbox Code Playgroud)
.directive('lettersOnly', function() {
return {
replace: true,
template: '<input replace="[^a-zA-Z]" with="">'
};
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10285 次 |
| 最近记录: |