Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS can a $on method be called more than once for a single $broadcast?

I'm seeing some very odd behaviour in my AngularJS app.

When a single $broadcast is made, the (only) receiver is fired twice.

The effect on the whole app is as if the receiver was only fired once. (i.e. only one of the item is added to the basket).

If you fire the $broadcast twice (i.e. click twice on the button which fires the $broadcast), you get four executions of the receiver, but a quantity of two items are correctly added to the basket.

Is there some spreadsheet-like recalculation going on here? Do $scope functions need to not affect 'plain' javascript variables?

My problem is that I've added an alert and it is being shown twice.


I've done some more work in debugging this:

I added a counter which counted the number of times the broadcast was received.

If the scope (without a dollar) is global, I get the doubled result. If its scope is local to the Ctlr function, I get a non-doubled result.

Could I have somehow created two instances of my controller?

I can see from firebug that $http ajax requests done from the controller only occur once, so I am very confused.

like image 653
fadedbee Avatar asked Jul 21 '12 11:07

fadedbee


People also ask

What is the difference between$ emit and$ broadcast?

The difference between $broadcast and $emit is that the former sends the event downwards from parent to child controllers, while $emit sends an event upwards from the current controller to all of its parent controllers.

What is the difference between emit and broadcast in AngularJS?

The difference between $broadcast() and $emit() is that the $broadcast() sends the event from the current controller to all of its child controllers. The $emit() method sends an event from current controller to all of its parent controllers.

How broadcast works in Angular?

$broadcast() as well as $emit() allow you to raise an event in your AngularJS application. The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers.


1 Answers

I would start by adding a console.log statement into the body of your controller to see how many times it's initialized. The lifecycle for controllers can be short since they tied to DOM elements which can be created and destroyed frequently.

If you are using the $routeProvider, are you specifying a value for the "controller" property? If so, are you also specifying the same controller in a partial using the "ng-controller" attribute? You really want to pick one or the other, not both, otherwise two controller instances will be created each time you navigate to that route.

like image 95
cliff.meyers Avatar answered Jan 16 '23 12:01

cliff.meyers