角度が必要なディレクティブは私自身のものを破る
-
21-12-2019 - |
質問
私はカスタム指令を持っています、の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;
});
}
};
})
.
は一人で動作しますが、明らかに、標準指令必須、失敗し始めます。
input(type='text' , required, onlydigitinput, min='1', max='99', maxlength='2')
.
それが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 ;
. 所属していません StackOverflow