adam0101 adam0101 - 3 months ago 13
Javascript Question

Detect if event listener is attached to directive in Angular

In my directive, I have the following event defined:

function wizard() {
return {
scope: {
raiseCancel: '&onCancel'
},


And then further down, I attempt to check if a listener is attached. If one is not, I want to execute some default behavior.

if (scope.raiseCancel) scope.raiseCancel();
else $window.history.back();


But apparently
scope.raiseCancel
will always be truthy because Angular assigns an anonymous function that calls
angular.noop
when no event listener is attached. How can I detect if there is a listener for my event?

Answer

You should handle your raiseCancel as an event handler, returning false to prevent the default behaviour.

Of course that mean code change in the raiseCancel handler(s) passed

if (scope.raiseCancel == null || scope.raiseCancel() !== false) {
    $window.history.back();
} 
Comments