【问题标题】:angular require directive breaks my own one角度要求指令打破了我自己的
【发布时间】:2014-06-03 08:57:58
【问题描述】:

我有一个自定义指令,在 filters on ng-model in an input 之后创建,将输入限制为数字:

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

单独使用效果很好,但显然与标准指令必需一起使用,它开始失败。

我使用如下 HTML(jade 语法):

input(type='text' , required, onlydigitinput,  min='1', max='99', maxlength='2')

(我不使用 type='number' 因为它与 maxlength:maxlength ignored for input type="number" in Chrome 混淆,并且也忽略了我的指令)

当我输入数字时,它工作正常。字段有效。 当我尝试输入数字然后输入一些字母时,它工作正常:字段有效,我无法输入非数字。 但是当我从非数字开始时,字段无效但我仍然可以输入字母,并伴有以下错误:

TypeError: Cannot read property 'toLowerCase' of undefined
at http://localhost:3000/scripts/core/directives/systemDirectives.js:63:54

指上面指令中 toLowerCase 的使用。请告知我如何清除此错误并使我的指令在后一种情况下也能很好地执行,并避免该错误。

【问题讨论】:

  • 好像是work fine。有什么问题?
  • @ExpertSystem 如果您在输入中添加必需的指令,它开始允许字母。

标签: javascript angularjs angularjs-directive


【解决方案1】:

您在输入字段上有一个必填字段验证器。因此,当您将字段设置为空白(“”)时 - 发生在您键入非数字时。该值变为未定义

var transformedInput = inputValue.toLowerCase().replace(/ /g, '')
              .replace(/[^0-9]+/g, '');
            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

在上面的代码之上添加以下内容:

if(!inputValue) return ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多