写一个ng-pattern允许特殊文本和数字

时间:2015-01-13 09:04:49

标签: angularjs

我有表格。我想允许输入特殊文本和仅限数字。 示例:允许号码和特殊文本" N / A"或者可能" NA"。

<input type="text" class="form-control" ng-model="UpdateKPI.KPIInPeriodInMonth" ng-pattern="/^\d+$/" required>

请帮帮我:

1 个答案:

答案 0 :(得分:1)

You can do it with custom directive :-
  <input type="text" ng-model="number" required="required" numbers-only="numbers-only" />

Js:
angular.module('myApp', []).directive('numbersOnly', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
       modelCtrl.$parsers.push(function (inputValue) {
           // this next if is necessary for when using ng-required on your input. 
           // In such cases, when a letter is typed first, this parser will be called
           // again, and the 2nd time, the value will be undefined
           if (inputValue == undefined) return '' 
           var transformedInput = inputValue.replace(/[^0-9+.]/g, ''); 
           if (transformedInput!=inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
           }         

           return transformedInput;         
       });
     }
   };
});

function MyCtrl($scope) {
    $scope.number = ''
}