Angularjs:禁用tab键默认行为 [英] Angularjs : disable tab key default behaviour

查看:258
本文介绍了Angularjs:禁用tab键默认行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个输入表。

我想要的是:当使用时按'+'键(光标在表格行中的任何地方),app在表中添加一个新行。

它可以正常工作:

I am developping a table of inputs.
What I want is : when use presses '+' key (wherever the cursor is in the table row), the app adds a new line in the table.
It works fine doing this :

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

我的问题是当用户在输入中按标签键时行转到下一个输入,下一个输入值是突出显示(这是tab键的正常行为)。

然后如果用户按'+'要添加新行,它会用+符号替换输入值。

My problem is that when user presses tab key in an input of the row to go to next input, the next input value is highlighted (which is the normal behaviour of tab key).
Then if user presses '+' to add a new line, it replaces the value of the input by the '+' sign.

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

I have set up a directive to allow user only to type number in the inputs, but it doesnt work when the input value is highlighted.

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键的默认行为。

If someone knows a way to prevent user from replacing highlighted value by the '+'.... or to disable the default behaviour of tab key.

提前致谢。

推荐答案

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

You can override the default action of the '+' key using a custom directive.

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
        }
      });
    };
  }]);

然后将其应用于输入,如下所示:

Then apply it to the inputs like so:

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

请参阅此处获取示例

这篇关于Angularjs:禁用tab键默认行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆