我创建了Cordova离子应用程序。我试过下面的代码。该指令在ios中运行良好,但在Android中运行不正常。它允许用户输入特殊字符。任何人都可以告诉我如何解决这个问题。
Register.html
<label class="item item-input"> <span><i
class="icon ion-ios-telephone-outline"></i></span> <input type="number"
ng-pattern="/^[0-9]{10,10}$/" placeholder="Mobile" only-num
ng-model="register.mobile_number" name="mobile" ng-minlength="10"
ng-maxlength="10" required>
</label>
app.js
app.directive('onlyNum', function() {
return function(scope, element, attrs) {
var keyCode = [8,9,37,39,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110];
element.bind("keydown", function(event) {
console.log($.inArray(event.which,keyCode));
if($.inArray(event.which,keyCode) == -1) {
scope.$apply(function(){
scope.$eval(attrs.onlyNum);
event.preventDefault();
});
event.preventDefault();
}
});
};
});
我也试过以下指令:
Register.html
<label class="item item-input"> <span><i
class="icon ion-ios-telephone-outline"></i></span> <input type="number"
ng-pattern="/^[0-9]{10,10}$/" placeholder="Mobile" allow-pattern="\d"
ng-model="register.mobile_number" name="mobile" ng-minlength="10"
ng-maxlength="10" required>
</label>
app.js
app.directive('allowPattern', [allowPatternDirective]);
function allowPatternDirective() {
return {
restrict: "A",
compile: function(tElement, tAttrs) {
return function(scope, element, attrs) {
// I handle key events
element.bind("keypress", function(event) {
var keyCode = event.which || event.keyCode; // I safely get the keyCode pressed from the event.
var keyCodeChar = String.fromCharCode(keyCode); // I determine the char from the keyCode.
// If the keyCode char does not match the allowed Regex Pattern, then don't allow the input into the field.
if (!keyCodeChar.match(new RegExp(attrs.allowPattern, "i"))) {
event.preventDefault();
return false;
}
});
};
}
};
};
答案 0 :(得分:0)
请使用此指令,它只允许数字
app.directive('numbersOnly', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined)
return '';
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput !== inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
})
请在您的输入文件中包含此指令
<input type="text" numbers-only>
这对我来说很好