Pete
Pete

Reputation: 4622

AngularJS delay run() method until controllers loaded

My module run() method checks if a user is logged in, then decides which view to load. The view slides in with a CSS animation, but as the animation is triggered (via - classlist.add() - I want to broadcast an event and get the controller to respond to that:

var myApp = angular.module('myApp', []);
run( function( $rootScope ) {

        $rootScope.loadView = function( view, animation ){ 
            // trigger the animation, which sends the $scope.$broadcast();
        }

        if(localStorage.loggedIn == 'false') {
            $rootScope.loadView( 'TutorialView' );
        } else {
            $rootScope.loadView(  'InterestView', 'slideUp');
        }
    }
);

myApp.controller('TutorialCtrl', ['$scope', function( $scope ){
    console.log('loaded');
    $scope.$on('TutorialViewCalled', function( event ) {
        console.log('tutorial class called');
    });         
}]);

In the service that does the animation I've got this code:

console.log('the broadcast is: ' + targetClass+'Called');
$rootScope.$broadcast( targetClass + 'Called' );
console.log('broadcast the call');

My console.log() outputs look like this:

the broadcast is: TutorialViewCalled
broadcast the call
loaded

So when the loadView() is called in run(), the TutorialCtrl hasn't yet been loaded. Any subsequent animations are fine, which I'm triggering with buttons in the view:

the broadcast is: InterestViewCalled
interest class called
broadcast the call
interest class loaded 

So it looks like the run() method is running before my controllers are ready. Am I not using run() properly, I assumed it would be the last thing to actually run, waiting for everything else to be loaded first.

Upvotes: 1

Views: 2219

Answers (1)

Pete
Pete

Reputation: 4622

So my solution to this was to get a list of all controllers on a module, and at the end of each one broadcast a "Loaded FooCtrl" event.

I stored the controller name in an array in the rootScope, then did a sort() and join() and checked the string matched with the controllers gathered from a method similar to this: https://gist.github.com/Willshaw/6621360

If the 2 strings matched, I knew all controllers where loaded and I could run my app.

Upvotes: 1

Related Questions