2016-05-13 53 views
1

我需要防止輸入字段中輸入的某些符號出現。當用戶在輸入中輸入某些內容時,我需要檢查它是否符合某個標準,如果符合 - 符號應該出現在輸入中(如往常一樣),但如果不符合,則不會發生任何事情。刪除在輸入中輸入的符號

那麼,有一些事件我能趕上之前輸入符號出現在輸入?

Plunker

<body ng-app="changeExample"> 
    <script> 
    angular.module('changeExample', []) 
     .controller('ExampleController', ['$scope', function($scope) { 
     $scope.var = 'a'; 
     }]) 

     .directive('changeValue', function() { 
     return { 
      require: 'ngModel', 
      link: function(scope, elem, attrs, ctrl) { 
      elem.on('input', function() { 
       if(ctrl.$viewValue !== 'a') { 
       scope.var = ''; 
       } 
      }); 

      ctrl.$formatters.push(function(value) { 
       return value === 'a' ? value : ''; 
      }); 
      } 
     } 
     }); 
    </script> 
    <div ng-controller="ExampleController"> 
    <input type="text" ng-model="confirmed" change-value ng-change="change()"/> 
    </div> 
</body> 
+0

[Plunker(https://plnkr.co/edit/ueyvq5vNjWoNSHkyEyM7?p=preview) –

+0

我已經編輯你的問題的重要部分。如果我錯過了你的問題,請隨時再次編輯。 – Zanon

+0

謝謝。我想,這就是我需要的 –

回答

1

可以使用ngChange指令來識別和刪除不想要的字符。

在下面的例子中,輸入字段將不接受$標誌。

angular.module('changeExample', []) 
 
    .controller('ExampleController', ['$scope', function($scope) { 
 
    
 
    var FORBIDDEN_SYMBOL = '$'; 
 
     
 
    $scope.change = function() { 
 

 
     var newChar = $scope.confirmed.slice(-1); 
 

 
     if (newChar === FORBIDDEN_SYMBOL) { 
 
     
 
     var inputSize = $scope.confirmed.length; 
 
     $scope.confirmed = $scope.confirmed.substring(0, inputSize -1); 
 
     } 
 
    } 
 
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="changeExample" ng-controller="ExampleController"> 
 
    <input type="text" ng-model="confirmed" ng-change="change()" /> 
 
</div>