2015-06-26 90 views

回答

2

您可以使用过滤器实现这一目标:http://jsfiddle.net/uhmgp23h/2/

<body ng-app="MyApp"> 
    <div ng-controller="MyController"> 
     <input type="text" ng-model="zip" /> 
    </div> 
</body> 

JS

var app = angular.module('MyApp',[]); 
app.controller('MyController', function($scope, $filter) 
{ 
    $scope.zip = ''; 
    $scope.$watch('zip', function(newVal, oldVal) 
    { 
     var value = String(newVal); 
     var number = value.replace(/[^0-9]+/g,''); 
     $scope.zip = $filter('numberFixedLen')(number,5); 
    }); 
}); 

app.filter('numberFixedLen', function() 
{ 
     return function(n, len) 
     { 
      var num = parseInt(n); 
      if (String(num).length > len) return n.substring(0, len); 
      return num; 
     }; 
}); 

这个过滤器会现场限制只有数字,也将其限制为5个字符。此过滤器可以处理任意数量的字符,只需将5更改为此行中的任何内容即可$filter('numberFixedLen')(number,5);

+0

感谢您使用此解决方案。您能否解释一下这可以如何处理'材料设计'指令'md-autocomplete'。 –

+0

我不熟悉那个指令 – Ronnie