9

I have some data that is being processed asynchronously in the background and want to delay the initialization of the entire AngularJS application until this finished.

BackgroundData.initialized is a Q promise, so something like this:

BackgroundData.initialized.then(AngularDoYoStuff)

The problem I run into is the home page's controller starts its initialization procedure, hits BackgroundData and either it has the wrong/no data.

What function can I wrap Angular's initialization in so, instead of just dom-ready, it waits for both dom-ready and BackgroundData.initialization?

UPDATE

I have gotten closer with the documentation on manual bootstrapping:

angular.element(document).ready ->
  setupGA()
  window.BackgroundData = new DataMachine()
  BackgroundData.initialized.then ->
    angular.bootstrap(document)

But when the controller files load (after this file), they are still getting initialized before BackgroundData is defined

UPDATE 2

Removing the ng-app directive in the HTML seems to have fixed the problem (since that was telling Angular to auto-init) but now it just ignores all of my angular.module calls

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Chris
  • 11,819
  • 19
  • 91
  • 145

3 Answers3

9

The problem was that I had left the ng-app directive in the html tag, which tells Angular to auto-initialize that scope. Removing it allowed my manual initialization to run correctly.

Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
Chris
  • 11,819
  • 19
  • 91
  • 145
3

as Chris mentioned, it can be done with angular.bootstrap and not mentioning the ng-app:

<div id="appArea" ng-controller="someCtrl">
  {{name}}
</div>

    <script>
    angular.module('someApp', [])
    .controller('someCtrl', function($scope) {
      $scope.name = "test name";
    })
    setTimeout(function() {
      angular.bootstrap(document, ['someApp']);
    }, 2000);
  </script>
Yar
  • 7,020
  • 11
  • 49
  • 69
0

One way to approach this if you are using routes in your app is to have the app initialize but wait on defining routes until the data is available.

I.e. provide a user-friendly 'loading' message, and then load functionality after.

You are able to inject $route where required, and then call something like:

$route.routes["/RouteName/:param"] = {templateUrl:"template.html", reloadOnSearch:true, controller:"ControllerName"};

After that, call $route.reload() or $rootScope.apply() to refresh.

More information at https://groups.google.com/forum/?fromgroups=#!msg/angular/AokZpUhZ6mw/x2kPIN2VAC0J

Alex Osborn
  • 9,831
  • 3
  • 33
  • 44
  • It seems like the routes are getting loaded – I created a MainController that then just calls $route.reload() right away. Logging $route.routes, I can see the correct routes there but $location.path() is empty so it doesn't match anything – Chris Mar 12 '13 at 20:27
  • and I confirmed it has no idea what path to render by adding an `otherwise` to the $routeProvider. – Chris Mar 12 '13 at 20:33