Delay Angular App Initialization

2019-04-06 06:31发布

I have some data that is being processed asynchronously in the background and want to delay the initialization of the entire Angular 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

3条回答
霸刀☆藐视天下
2楼-- · 2019-04-06 07:06

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>
查看更多
成全新的幸福
3楼-- · 2019-04-06 07:15

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

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-06 07:17

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.

查看更多
登录 后发表回答