我有一个功能如下:
在Androids(三星Galaxy S4,版本3.4)本机浏览器上,会发生这种情况:
有什么想法吗?
<div ng-app="test">
<input type="text" cardnr ng-model="model" maxlength="9"/>
</div>
angular.module('test', []);
angular.module('test').directive('cardnr', function () {
'use strict';
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function handlePastedValues(val) {
if (val === undefined) {
return;
}
if (val.length > 9) {
val = val.substring(0, 9);
}
if (val.charAt(4) !== ' ') {
val = val.substring(0, 8);
}
if (val.length > 5 && val.charAt(4) !== ' ') {
val = val.substr(0, 4) + ' ' + val.substr(4);
ngModelCtrl.$setViewValue(val);
ngModelCtrl.$render();
}
return val;
});
ngModelCtrl.$parsers.push(function removeIllegalCharacters(val) {
if (val === undefined) {
return;
}
var clean = val.replace(/[^0-9 ]+/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
ngModelCtrl.$parsers.push(function insertSpaceAfterFourCharacters(val) {
if (val === undefined) {
return;
}
if (val.length == 4) {
ngModelCtrl.$setViewValue(val + ' ');
ngModelCtrl.$render();
}
return val;
});
element.bind('keydown', function (event) {
var BACKSPACE = 8,
DELETE = 46,
SPACE = 32;
if (event.keyCode === BACKSPACE || event.keyCode === DELETE) {
if (ngModelCtrl.$viewValue.length === 5) {
ngModelCtrl.$setViewValue(ngModelCtrl.$viewValue.substring(0, 3));
ngModelCtrl.$render();
event.preventDefault();
}
}
if (event.keyCode === SPACE) {
event.preventDefault();
}
});
}
};
});