2016-08-24 60 views
0

我有一個字段,應該只接受數字,我通常知道我們做input type="number"。角度最好的方法是隻允許數字?只接受輸入字段中的數字。角度的方式(沒有html5)

+1

的可能的複製[angularjs:只允許數字被輸入到一個文本框(http://stackoverflow.com/questions/16091218/angularjs-allows-只能輸入文本框中的數字) – Oyeme

+0

選中[this](http://codepen.io/apuchkov/pen/ILjFr) – gianlucatursi

+0

您可以使用任一指令...函數.. ..模式.... –

回答

1

您可以創建一個指令類似如下,然後使用它的HTML元素屬性

.directive('validNumber', function() { 
     return { 
      restrict: 'A', 
      require: '?ngModel', 
      link: function (scope, element, attrs, ngModelCtrl) { 

       //8:"BACKSPACE",9:"TAB",17:"CTRL",18:"ALT",37:"LEFT", 
       //38:"UP",39:"RIGHT",40:"DOWN",45:"INSERT",46:"DELETE", 
       //48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9", 67:"C",86:"V", 
       //96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9", 
       //109:"-",110:".",144:"NUMLOCK", 189:"-",190:".", 

       var keyCode = [8, 9, 17, 37, 38, 39, 40, 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 67, 86, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 109, 110, 144, 189, 190]; 
       element.bind("keydown", function (event) { 
        if ($.inArray(event.which, keyCode) == -1) { 
         scope.$apply(function() { 
          scope.$eval(attrs.validNumber); 
          event.preventDefault(); 
         }); 
         event.preventDefault(); 
        } 

       }); 
      } 
     }; 
    }); 
0

也許你可以利用這個簡單的指令..

// ---Directive for Digit restriction on input fields.--------- 

myApp.directive('numbersOnly', function() { 
return { 
    require : 'ngModel', 
    link : function(scope, element, attrs, modelCtrl) { 
     modelCtrl.$parsers.push(function(inputValue) { 
      // if the input is 'undefined' 
      if (inputValue == undefined) 
       return '' 
      var transformedInput = inputValue.replace(/[^0-9]/g, ''); 
      if (transformedInput != inputValue) { 
       modelCtrl.$setViewValue(transformedInput); 
       modelCtrl.$render(); 
      } 

      return transformedInput; 
     }); 
    } 
}; 

}) ;

和在HTML中,你可以聲明的指令,因爲

<input type="numbers" numbers-only ng-model="numberModel"> 

所以,理想情況下,輸入字段將與數作爲唯一的數據更新模型..

這到底是怎麼發生的事情,每次按下某個字符時,它都會被我們的指令numbersOnly監控,這裏是您僅挑選數字作爲輸入的地方。

希望這有助於出... 乾杯

相關問題