0
我正在使用角度&試圖防止用戶在文本字段中輸入字母,並在相同的項目將模型推送到陣列上。但邏輯似乎並不完美,有時允許字母表。如何防止輸入特殊字符(如$,%)?防止用戶輸入字母並將模型推入陣列
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] = '';
}
});
演示:http://plnkr.co/edit/t8OE5uJ578zgkiUTjHgt?p=preview
關於字母和特殊字符,我很疑惑我們是否要禁止使用字母或特殊字符,這裏的正則表達式會移除特殊字符,但它可以用我們希望的任何正則表達式自定義。 –
謝謝你的plnk,它可以防止特殊字符被添加和精美地工作我如何定製正則表達式以防止字母? – user1184100
我在正則表達式方面並不擅長,但在線數以千計,但例如:'/ [^ 0-9]/g'只允許數字。 –