本文介绍了指令限制输入不与类型=一些工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个限制输入到特定的符号,在我的情况下,只有数字的自定义指令。它是在angularjs在输入 NG-模型过滤器和它的文本型INPIT正常工作。

I have a custom directive that restricts input to specific symbols, in my case, only numbers. It is made after angularjs filters on ng-model in an input and it works fine in text-type inpit.

指令声明为

     .directive('onlydigitinput', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                var transformedInput = inputValue.toLowerCase().replace(/ /g, '').replace(/[^0-9]+/g, '');
                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
})

但在数字输入的情况下,我想用输入类型=数字,不是type =文本:

but in case of numerical input I want to use input type=number, not type=text:

<input type="number"
onlydigitinput="onlydigitinput" required="required" min="1" max="99" maxlength="2">

,然后这是一个问题:我有正确的验证基于最小 - 最大属性,但我仍然可以进入所有的符号,如字母,指令不因为它应该工作。此外,最大长度似乎没有效果。我如何可能解决我的指令类型为数字的投入工作?

and then it's a problem: I have correct validation based on min-max attribute, but I still can enter all symbols, such as letters, and directive does not work as it should. Additionally, maxlength seems not to have effect. How I can possibly fix my directive to work with type="number" inputs?

推荐答案

这里有两个问题。首先,最大长度属性不随输入型数量工作。例如参见
maxlength忽视了在Chrome浏览器输入类型=数字。

There are two issues here. First, the maxlength attribute doesn't work with input type number. See e.g.maxlength ignored for input type="number" in Chrome.

其次,当输入类型为数量,你的指令的功能,只得到了 inputValue将参数时的值它的一个数字。请参见为例(控制台输出可能会使其更清晰)。

Second, when the input type is number, your directive's function only gets a value for the inputValue parameter when it's a number. See this fiddle as an example (the console output might make it clearer).

编辑:

如何关键的是它为您使用的数字类型的输入?如果微调控制了浏览器添加到输入字段它是不是必须的,我可能会去这里描述就像一个自定义类型:How在Angular.js创建一个自定义输入类型?

How crucial is it for you to use the number type input? If the spinner controls that browsers add to the input field for it aren't a necessity, I'd probably go for a custom type like described here: How to create a custom input type in Angular.js?

我已经用于例如非常类似的东西钱输入字段(本地化的小数点分隔符等等)。

I've used something very similar for e.g. money input fields (with localized decimal separators etc.).

这篇关于指令限制输入不与类型=一些工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 06:18