Angularjs:禁用tab键默认行为

时间:2016-01-19 14:24:18

标签: javascript jquery angularjs

我正在制定一份投入表 我想要的是:当使用时按'+'键(光标在表格行中的任何位置),应用程序在表格中添加一个新行。
这样做很好:

<tr ng-repeat="sell in sells"  ng-keypress="newLine($event)">

我的问题是当用户在行的输入中按标签键转到下一个输入时,下一个输入值是突出显示(这是正常行为tab键) 然后,如果用户按'+'添加新行,则会使用“+”符号替换输入值。

我已经设置了一个指令,允许用户只在输入中键入数字,但是当输入值突出显示时它不起作用。

angular.module('myApp').directive('numbersOnly', function($timeout) {
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
       modelCtrl.$parsers.push(function (inputValue) {
           // this next if is necessary for when using ng-required on your input. 
           // In such cases, when a letter is typed first, this parser will be called
           // again, and the 2nd time, the value will be undefined
           if (inputValue == undefined) return '' 
           var transformedInput = inputValue.replace(/[^0-9.]+/g, ''); 
           if (transformedInput!=inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
           }         

           return transformedInput;         
       });
     }
   };
});

<td style="width:59px"><input type="text" ng-model="sell.quantity" numbers-only enter-as-tab ></td>

如果有人知道阻止用户用'+'替换突出显示值的方法....或者禁用tab键的默认行为。

enter image description here

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用自定义指令覆盖“+”键的默认操作。

module.directive('overridePlusKey', ['$window', function ($window) {
    // Linker function
    return function (scope, element, attrs) {
      element.bind('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        console.log(keyCode);
        if (keyCode == 107 || keyCode == 187)
        {
          e.preventDefault();
          // Your code here to add a row
        }
      });
    };
  }]);

然后将其应用于输入:

<input type="text" ng-model="content" override-plus-key />

See here for an example

答案 1 :(得分:0)

使用表单验证甚至是ng-change处理程序可能会做得更好,但如果您希望坚持使用现有的$parser方法,则可以使用$modelValue恢复原始值:

angular.module('myapp', []).directive('numbersOnly', function($timeout) {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {
        if (inputValue == undefined) return '';
        var transformedInput = inputValue.replace(/[^0-9.]+/g, '');
        if (transformedInput != inputValue) {
          modelCtrl.$setViewValue(modelCtrl.$modelValue);
          modelCtrl.$render();
          if (inputValue.indexOf('+') > -1) {
            alert("Perhaps trigger your newLine() here");
          }
          return modelCtrl.$modelValue;
        } else {
          return inputValue;
        }
      });
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <input type="text" ng-model="sell.quantity" numbers-only enter-as-tab>
</div>

请不要尝试禁用Tab键。无障碍问题。 (用户期望tab键将执行tab键通常执行的操作。)

相关问题