2014-10-12 43 views

回答

0

我覺得你的指令太依賴你的模型,它是不是一個好主意的指令,瞭解模型,我把主要的想法從How to allow only a number (digits and decimal point) to be typed in an input?

var app = angular.module('myApp', []); 

app.controller('MainCtrl', function($scope) { 
}); 

app.directive('validNumber', function() { 
    return { 
     require: '?ngModel', 
     link: function(scope, element, attrs, ngModelCtrl) { 
      if(ngModelCtrl) { 
       ngModelCtrl.$parsers.push(function(val) { 
       //this will stop your from adding inputs that aren't numbers, you can change it to just affect validity 
       var clean = val.replace(/[^0-9]+/g, ''); 
       if (val !== clean) {      
        ngModelCtrl.$setViewValue(clean); 
        ngModelCtrl.$render(); 
       } 
       return clean;     
      }); 
      } 
      else { 
       element.bind('keypress', function(event) { 
        //your logic here, not sure if you want to ignore or add or whatever you want to      do without a model, this is the place 
        var newVal = element.val() + String.fromCharCode(event.keyCode); 
        //check if newVal is ok for your and then set validity 
       }); 
      } 
    }; 
}); 

另一種方法是推入$解析器只有一個有效性檢查,而不是替換值:

ngModel.$parsers.unshift(function(value) { 
     var valid = angular.isNumber(value); 
     ngModel.$setValidity('isNumber', valid); 
     return valid ? value : undefined; 
}); 

希望這會有所幫助。

0

如果限制打字不是問題並且您支持IE10 +,則可以考慮使用HTML5數字輸入字段(例如<input type="number"/>

相關問題