gpt4 book ai didi

javascript - 阻止用户输入字母并将模型插入数组

转载 作者:行者123 更新时间:2023-12-02 17:41:32 25 4
gpt4 key购买 nike

我正在使用 Angular 并试图阻止用户在文本字段中输入字母,并在同一项目中将模型推到数组上。但逻辑似乎并不完美,有时允许字母表。如何防止输入 $、% 等特殊字符?

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

最佳答案

试试这个:

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 .

关于javascript - 阻止用户输入字母并将模型插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22163502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com