Gautam Kumar Samal
Gautam Kumar Samal

Reputation: 838

$viewContentLoaded is executed before initializing root scope

Method on $viewcontentloaded is firing asynchronously. To detail my problem, I have a variable in root scope i.e. my Main controller, which need to be initialized before my view controller loads. In module.run I am calling a sync function to initialize $rootScope.session. And In my view controller of a route, I am checking the status of session in afunction that is called like

$scope.$on('$viewContentLoaded', function() {
            $scope.initialize();
        });

But some times on page refreash, I am getting an undefined value for $rootScope.session, as It may have initialized later. So, Is there any way to make this synchronous like rootscope will be initialized before view loads. And for curiosity, how it will affect, if I call the $scope.initialize(); normally in my controller, in $viewContentLoaded or in $routeChangeSuccess. Thanks in advance.

Upvotes: 1

Views: 826

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24617

So, Is there any way to make this synchronous like rootscope will be initialized before view loads.

Use the $controller service to manually create the controller, as in a unit test.

  $controllerProvider.register('FooCtrl', FooCtrl);
  ctrl = $controller('FooCtrl', {$scope: scope});

Or $broadcast a custom event from the main controller down to the child:

  function mainCtrl($rootScope)
    {
    $rootScope.$broadcast('abc');
    }

  function secondCtrl($scope)
   {
   $scope.$on('abc', function(event) { $scope.initialize(); });
   }

Or use a try/catch block and a recursive call with a timer.

These are more or less the steps that you would take to implement lazy loading in AngularJS. In summary, you would first define your app module to keep instances of the relevant providers. Then you would define your lazy artifacts to register themselves using the providers rather than the module API. Then using a ‘resolve’ function that returns a promise in your route definition, you would load all lazy artifacts and resolve the promise once they have been loaded. This ensures that all lazy artifacts will be available before the relevant route is rendered. Also, don’t forget to resolve the promise inside $rootScope.$apply, if the resolution will be happening outside of AngularJS. Then you would create a ‘bootstrap’ script that first loads the app module before bootstrapping the app. Finally, you would link to the bootstrap script from your ‘index.html’ file.

References

Upvotes: 0

Related Questions