Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs directives using templateUrl - initialisation sequence

I have scenario where I want to send a broadcast event in one controller and have the controller for a directive receive the message. The event is sent immediately on controller startup, and the issue is that because the directive is loading the view using templateUrl, it happens asynchronously, so the event is broadcast before the directive controller is intialised. This problem doesn't happen if the view is in the main page body, but I guess there could still be an issue with controller initialisation order.

I am using the following code in my main controller:

$rootScope.$broadcast("event:myevent");

I have reproduced the issue here: http://jsfiddle.net/jugglingcats/7Wf8N.

You can see in the Javascript console that the main controller is initialised before the controller for the directive, and it never sees the event.

So my question is whether there is a way to wait until all controllers are initialised before broadcasting an event?

Many thanks

like image 670
jugglingcats Avatar asked Feb 21 '26 13:02

jugglingcats


1 Answers

I have created a working version. I actually feel that it is a very unclean way to do it, but I could not come up with something better: http://jsfiddle.net/7Wf8N/3/

What I did is this: In the directive I added some code which will increase a counter in $rootScope upon initialization. I use a counter because as you said, you want to wait for more than one controller:

$rootScope.initialized = ( $rootScope.initialized||0 ) +1;

In the "RegularCtrl" I added a watch on this counter and if the counter reaches the correct value (everything is initialized) I send the event:

$rootScope.$watch('initialized', function() {
    if ( $rootScope.initialized == 1 ) {
        $rootScope.$broadcast("event:myevent");        
    }
});
like image 69
Juliane Holzt Avatar answered Feb 23 '26 02:02

Juliane Holzt