LargeCrimsonFish
LargeCrimsonFish

Reputation: 243

How to force an event.on('blur') event to be called before ng-blur event?

So this is mainly to guarantee backwards compatibility. I need to add additional functionality on blur to a large number of html elements without having to edit the controller methods called by the ng-blur attribute of those elements.

I wrote a directive to do this, but the problem is the directive method seems to always finish executing after the ng-blur methods in the controller. I need the directive method to finish executing before the ng-blur method in the controller begins.

Here is the basic format of the code:

<input test-directive ng-model="testValue" ng-blur="ngBlurTest(testValue)">

Directive:

angular.module('testDirectives', [])

.directive('testDirective', [ function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            ngModel: '=',
        },

        link: function (scope, element, attrs, ngModelCtrl, test) {
            element.bind('blur', function() {
                    console.log('This needs to appear first')
                }
            });
        }
    };  
}])

Controller (Method)

$scope.ngBlurTest = function(value) {
    console.log('TEST FROM CONTROLLER: ' + value);
}

Thanks for the help!

Upvotes: 0

Views: 373

Answers (1)

Frane Poljak
Frane Poljak

Reputation: 2365

I'm not sure if it's possible, but try setting priority of the directive to a really high number, for example:

.directive('testDirective', [ function() {
    return {
        priority: 1000000,
        restrict: 'A',
        ...

Also try using addEventListener, but don't forget to clear it:

var listener = function(event) {...};
element[0].addEventListener('blur', listener);
...
scope.$on('$destroy', function() {
    element[0].removeEventListener('blur', listener);
});

Also try setting useCapture parameter of addEventListener to true:

element[0].addEventListener('blur', listener, true);

Upvotes: 1

Related Questions