adam0101 adam0101 - 1 year ago 93
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
will always be truthy because Angular assigns an anonymous function that calls
when no event listener is attached. How can I detect if there is a listener for my event?

Answer Source

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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download