2016-02-08 114 views
0

我試圖編寫一個限制用戶輸入的指令。在示例limit-directive="2"上,用戶只能在輸入字段中輸入兩個字符。指令無法正常工作

我的問題是我的指令不工作。它被調用,但不會停止鍵返回false或event.preventDefault();。 關於我缺少什麼的任何想法?

export class limitDirective implements angular.IDirective { 
     restrict = 'A'; 

     constructor() { 
      if(console) console.log('limit directive invoked') 
     } 

     link = (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => { 
      var limit = parseInt(attrs.limitDirective); 

      angular.element(element).on("keypress", function(event) { 
       if (this.value.length >= limit){ 
        var allowedKeys = [8, 9, 13, 35, 36, 37, 38, 39, 40, 46]; 
        var key = event.which || event.keyCode; 

        if (allowedKeys.indexOf(key) < 0){ 
         event.preventDefault(); 
        } 

       } 
      }); 
     } 

     static factory(): angular.IDirectiveFactory { 
      const directive =() => new limitDirective(); 
      return directive; 
     } 
    } 
+0

你能提供一個小提琴嗎?我的猜測是你必須使用'keydown'事件而不是'keypress'。你也可能希望明確指定'parseInt'的基數,比如'parseInt(number,10)',因爲舊版本的EcmaScript使用八進制作爲默認基數。 – TeoMor

回答

0

我想你想如果是less than or equals運營商,而不是greater that or equals使用。我懷疑this對應的事件回調中的元素..我建議你這樣做:

element.bind("keypress", function(event) { 
       if (element[0].value.length <= limit){ 
        var allowedKeys = [8, 9, 13, 35, 36, 37, 38, 39, 40, 46]; 
        var key = event.which || event.keyCode; 
       if (allowedKeys.indexOf(key) < 0){ 
        event.preventDefault(); 
       } 

      } 
     });