2013-12-19 23 views
5

我有一個綁定到包含5位數字的變量的文本輸入。我怎樣才能阻止第一個數字,所以只有其他4個可編輯?阻止文本字段中的第一個數字

目前我有這樣的:ng-model="my_var" ng-pattern="/^\d{5}$/"

請注意,該值是雙向綁定,這意味着我展示它,用戶可以編輯/保存。

+0

你是如何獲得第一個數字? –

+0

@ Banana-In-Black從GET服務器接收到GET值後,該值保證有5位數字。 – alexandernst

回答

2

這裏是一個可行的解決方案(需要可能調整它一點點你的特殊需要):

app.directive("filterInput", function() { 

    return { 
     require: 'ngModel', // controller to ng-model needed 
     restrict: 'A', 

     link: function (scope, element, attrs, modelCtrl) { 

      var unchanged = attrs.filterInput; 
      var regex = /^\d{0,5}$/; // the RegExp (in more generic solution could be passed from outside) 

      modelCtrl.$parsers.push(function (inputValue) { // adding new $parser 

       if(inputValue[0] != unchanged){ // if the first digit is different from what it should be set value as the first digit 
        modelCtrl.$setViewValue(unchanged); 
        modelCtrl.$render(); 
        return unchanged; 
       } 

       if(inputValue.length > 5){ // trim the input if it is longer than five -- it is not generic at all 
        var rv = inputValue.substring(0,5); 

        modelCtrl.$setViewValue(rv); 
        modelCtrl.$render(); 

        return rv; 
       } 



       var transformedInput = regex.exec(inputValue); 

       if (transformedInput != null) { // check if pattern exists 
        transformedInput = transformedInput[0]; 
       } 
       else { 
        transformedInput = unchanged; // if not set the value to the not changeable part 
       } 

       if (transformedInput != inputValue) { // re-render if value changed 
        modelCtrl.$setViewValue(transformedInput); 
        modelCtrl.$render(); 
       } 
       return transformedInput; 
      }); 
     } 
    } 
}); 

以及如何使用它:

<p>var: {{my_var}}</p> 
<input type="text" ng-model="my_var" filter-input="1"/> 

PLNKR

順便說一句:它將允許只傳遞數字:-)

+0

此段錯誤:RangeError:超過最大調用堆棧大小 – alexandernst

+0

@alexandernst如果要使用它與ng-pattern - 作爲ng-pattern將$ modelValue設置爲undefined。您可以嘗試將指令的優先級更改爲高於ng-pattern的優先級,或者完全從ng-pattern退出,因爲無法輸入無效的輸入。你看過那個大笨蛋嗎? –

+0

所以...我刪除了ng-pattern,現在它不會讓我輸入比1位更遠的任何內容。你確定這個工作正常嗎? – alexandernst

0

也許不是最好的解決辦法,但它的工作原理:

HTML

<input ng-model="my_var" maxlength="5"> 

控制器

$scope.my_var = '1'; 
$scope.$watch('my_var', function(){ 
    if($scope.my_var.length != 1){ 
    if($scope.my_var.length == 0){ 
     $scope.my_var = '1'; 
    } 
    } 
}); 
+0

這不是我要求的 – alexandernst

+0

對不起,我讀的問題太快 – Renzzs

相關問題