質問

私はカスタム指令を持っています、のNGモデルでは、入力を桁数だけ制限します。

     .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 Syntax)を使用します。

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

それがMAXLENGTHで台無しとして(私は=「数」の型を使用しないでください。 Chrome で入力Type=" Number "では無視されるmaxlengthは、また私の指令も無視しています)

数字を入力するとうまく機能します。フィールドが有効です。 数字を入力してからいくつかの文字を入力しようとすると、Fine:フィールドが有効で、非数字を入力することはできません。 しかし、私が桁数以外から始めると、フィールドは無効ですが、それでも次のエラーが付いている文字を入力できます。

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

上記指令におけるTolowerCaseの使用を参照してください。このエラーを解消し、私の指令を後者の場合には演奏することができ、エラーを避けることができます。

役に立ちましたか?

解決

入力フィールドに必要なフィールドバリデータを持っています。したがって、フィールドを空白( "")に設定すると、非数字を入力すると起こります。値は未定義になります。

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

上記のコードの上に下記を追加します。

if(!inputValue) return ;
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top