我正在使用角度&试图阻止用户将字母输入文本字段并在同一项目中将模型推送到数组上。但逻辑似乎并不完美,有时允许使用字母表。如何防止输入$,%这样的特殊字符?
HTML
<ul>
<li ng-repeat="item in arr track by $index">
<input type="text" number ng-change="itemChange()" ng-model="item" />
<button ng-click="add()">Add Item</button>
</li>
</ul>
JS
app.directive('number', function(){
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl){
elem.bind('keyup', function(e) {
console.log(e)
var text = this.value;
this.value = text.replace(/[a-zA-Z]/g,'');
});
}
};
})
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.arr = [];
//Initialize with one element
$scope.arr[0] = '';
//Push when there is a change in the input
$scope.itemChange = function() {
$scope.arr[this.$index] = this.item;
}
//Add an empty item at the end
$scope.add = function() {
$scope.arr[$scope.arr.length] = '';
}
});
答案 0 :(得分:2)
试试这个:
app.directive('alphabetonly', function(){
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl){
ctrl.$parsers.push(function(inputValue) {
var transformedInput = inputValue.replace(/[^\w\s]/gi,'');
if (transformedInput != inputValue) {
ctrl.$setViewValue(transformedInput);
ctrl.$render();
}
return transformedInput;
});
}
};
})
请参阅plunk。