I'm currently working on a directive that restricts user input. With the limit-directive="2"
, the user should only be able to type in two characters in the input field.
Unfortunately, I'm facing an issue with my directive. It is being called, but it fails to prevent key presses using return false
or event.preventDefault();
.
Any suggestions on what might be causing this problem?
export class limitDirective implements angular.IDirective {
restrict = 'A';
constructor() {
if(console) console.log('limit directive invoked')
}
link = (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => {
var limit = parseInt(attrs.limitDirective);
angular.element(element).on("keypress", function(event) {
if (this.value.length >= limit){
var allowedKeys = [8, 9, 13, 35, 36, 37, 38, 39, 40, 46];
var key = event.which || event.keyCode;
if (allowedKeys.indexOf(key) < 0 ){
event.preventDefault();
}
}
});
}
static factory(): angular.IDirectiveFactory {
const directive = () => new limitDirective();
return directive;
}
}