Akin Dönmez February 2016

directive doesn't function properly

I'm trying to write a directive which limits the input of the user. On the example limit-directive="2", the user can only type two characters in the input field.

My problem is that my directive is not working. It is invoked but doesn't stop the key press with return false or also event.preventDefault();. Any ideas on what am I missing ?

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;
        }
    }

Answers


Raulucco February 2016

I think you want to use a if is less than or equals to operator instead of the greater that or equals. And i doubt that this correspond to the element in the callback of the event.. I suggest you do:

 element.bind("keypress", function(event) {
                if (element[0].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();
                }

            }
        });

Post Status

Asked in February 2016
Viewed 2,511 times
Voted 9
Answered 1 times

Search




Leave an answer