2013-03-21 16 views
20

我必須爲IE8編寫一些代碼。我有一個NG重複創建填充表:角度指令忽略非數字輸入

<input production-qty type="text" class="input-mini" maxlength="3" ng-model="day.qtyA" ui-event="{ blur : 'updateProduction(day)' }" ng-disabled="day.type=='H'"> 

IE8不會做類型=數字

我想一個指令,將忽略該輸入字段沒有數字鍵的鍵擊。 ... ie 0 - 9

我不想讓用戶輸入abc並污染模型,然後告訴他們這個值是無效的。我寧願不讓他們輸入任何首先無效的數據。

+0

見http://stackoverflow.com/a/12947995/215945爲如何建立一個自定義的驗證實例。 – 2013-03-21 18:17:50

+0

我不明白這對我有何幫助。我不只是試圖阻止數據進入模型......而是從屏幕上出現。我想通過使用type = text來實現input type = number – Jason 2013-03-21 18:33:01

+0

對不起,這不是太有用。$解析器可用於過濾輸入文本框中顯示的內容。請看我在我的回答中寫的那篇文章。 – 2013-03-21 19:40:41

回答

43

HTML:

<input production-qty type="text" maxlength="3" ng-model="qty1"> 

指令:

app.directive('productionQty', function() { 
    return { 
    require: 'ngModel', 
    link: function (scope, element, attr, ngModelCtrl) { 
     function fromUser(text) { 
     var transformedInput = text.replace(/[^0-9]/g, ''); 
     console.log(transformedInput); 
     if(transformedInput !== text) { 
      ngModelCtrl.$setViewValue(transformedInput); 
      ngModelCtrl.$render(); 
     } 
     return transformedInput; // or return Number(transformedInput) 
     } 
     ngModelCtrl.$parsers.push(fromUser); 
    } 
    }; 
}); 

Plunker

參見filters on ng-model in an input。我上面的答案是模仿pkozlowski.opensource的答案。

我看着ng-pattern,但它不過濾文本框中顯示的內容。它將$scope.qty1設置爲undefined,但不需要的字符在文本框中可見。

+0

「我看着ng-pattern,但它不會過濾文本框中顯示的內容」 - 完全......我會試試看看它是如何工作的...感謝您的幫助! – Jason 2013-03-22 13:10:45

+0

awesome .... made one change:return Number(transformedInput); – Jason 2013-03-22 15:33:04

+1

這對我不起作用,如果(text === undefined)返回文本,我不得不在函數的第一行添加如下代碼: – epitka 2013-11-26 21:24:12

0

首先包括在js文件的代碼 numericInput.js

指令: -

.directive('numeric', function() { 
    return function(scope, element, attrs) { 

     $(element[0]).numericInput({ allowFloat: true }); 

    }; 
}) 

HTML: -

<input type="text" numeric /> 

DEMONumeric Demo

+1

嘗試輸入一個負數 – 2013-12-12 01:35:16

+0

使用此 ...但您仍然沒有寫減號,您必須使用向下箭頭鍵輸入負數 – 2013-12-16 04:10:05

-2

不是指令,但我只使用:

控制器:

$scope.blockNonNumber = function (val, field){ 

     $scope[field] = val.toString().replace(/[^0-9]/g, ''); 

    } 

HTML:

<input type="text" ng-model="price" ng-change="blockNonNumber(price, 'price')" pattern="[0-99]"> 

它不是指令,但可以在指令中被用作wellside

8

HTML:

<input type="number" name="graduationYear" ng-model="gradYear" only-num> 

指令:

directive('onlyNum', function() { 
    return function(scope, element, attrs) { 

     var keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110]; 
     element.bind("keydown", function(event) { 
      //console.log($.inArray(event.which,keyCode)); 
      if ($.inArray(event.which, keyCode) === -1) { 
       scope.$apply(function() { 
        scope.$eval(attrs.onlyNum); 
        event.preventDefault(); 
       }); 
       event.preventDefault(); 
      } 

     }); 
    }; 
});