amichai amichai - 6 months ago 16
AngularJS Question

bind regular custom js event to angular controller function

I'm trying to bind angular function to regular js event (logedIn event) using angular directive as described here.

The directive code is:

evApp.directive('onlogin', function () {
return {
restrict: 'A',
transclude: true,
scope: {
'onlogin': '&'
},
link:function (scope, element, attr) {
//Code to detect when element is pulled goes here
document.addEventListener("logedIn", function (e) {
scope.$eval(attr.onlogin);
});
}
}
});


The html tag is:

<div onlogin="loggedIn()"></div>


Its worked but I didn't found a way to pass the parameter 'e' that arrived with the event in the link function. I tried to pass from the html the function handler only and call the function with the parameters from the link function but it didn't worked.
some thing like:

<div onlogin="loggedIn"></div>


Thanks, Amichai

Answer

you should add scope.$apply to let angular now that it needs to fire digest cycle and then just call scope.onlogin({e: e}) basically you can use it in handler, as you would use $event.

 evApp.directive('onlogin', function () {
return {
    restrict: 'A',
    transclude: true,
    scope: {
        'onlogin': '&'
    },
    link:function (scope, element, attr) {
        //Code to detect when element is pulled goes here
        document.addEventListener("logedIn", function (e) {
            scope.$apply(function () {
             scope.onlogin({e: e})
            });
        });
    }
}
});