防止用户输入字母&将模型推入数组

时间:2014-03-04 05:16:32

标签: javascript angularjs

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

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

1 个答案:

答案 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