2015-06-26 92 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