2014-10-12 13 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"/>

相关问题