byCoder
byCoder

Reputation: 9184

AngularJS: directive multiple time on page and emit/broadcast handling

I have such strange issue:

When in my view i have declared directive 2 (and more) times i get such magic:

controller:

      $scope.$broadcast('slideableClose');

and directive:

      scope.$on('slideableClose', function(event) {
        console.log('slideableClose');
        action();
      });

and when i broadcast my data, i see in console that it is called twice

how can i call it only one time, becouse it must be fired only once, but i need multiple directives on my page?

Upvotes: 0

Views: 417

Answers (1)

ArslanW
ArslanW

Reputation: 353

Hmm, I have a way which can be used to accomplish firing only once, but it requires maintenance and two way binding between your controller and directives for this variable.

You could define a scope variable:

isHandled = false

Now whenever the event is fired, set this value to false and make your handler something like this:

scope.$on('slideableClose', function(event) {
    if (isHandled) {
      return;
    }
    console.log('slideableClose');
    action();
  });

Now if this event is already handled it won't be handled again. Otherwise it will be handled. Remember to set this variable to false when the event itself is fired or before it's fired.

Upvotes: 1

Related Questions