Alex Haines
Alex Haines

Reputation: 47

Manually bootstrap angular app to create async app initialization

I am trying to manually bootstrap my angular app in order to load some data asynchronously that my app relies on. See this article

The problem is no matter what I try I cant get access to an instance of a factory using angular.injector. See this plunker

The problem is anytime I run code like this:

var Injector = angular.injector(["MyAPP", "ng"]);
var initService = Injector.get("MyService");

I just get unknown provider errors.

Can someone please help me make this plunker work, or point me to a better way to create an angular app initialization service. thanks,

Upvotes: 0

Views: 1077

Answers (2)

David Atchley
David Atchley

Reputation: 1204

Edited: Updated to reflect our discussion in the comments thread.

To setup the initApp() function to initialize, asynchronously using a Promise, any app level services required, including the factories (as defined in the original plunker) you can have it simply return a Promise that will resolve when the initial injections are complete; and once that is done, call your bootstrapApplication() method to bootstrap Angular on the page.

function initApp() {
  return new Promise(function(resolve, reject) {
        var Injector = angular.injector(["ng","plunker"]);
        Injector.invoke(['factoryTwo', function(factoryTwo) { 
          console.log(factoryTwo.test);
          resolve();
        }]);
  });
}


function bootstrapApplication() {
  angular.element(document).ready(function() {
      angular.bootstrap(document, ["plunker"]);
  });
}  

initApp().then(bootstrapApplication);

Here's a link to the forked plunker with the above code snippet working: http://plnkr.co/edit/764AqLZf6rQHwPZ1RAZc?p=preview

Upvotes: 1

S. Ali Mihandoost
S. Ali Mihandoost

Reputation: 3104

you must bootstrap loaded ajax content before insert in page

You need to call $compile on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.

In your fiddle, it would look something like this.

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);

Obviously, $compile must be injected into your controller for this to work.

Read more in the $compile documentation.

Upvotes: 0

Related Questions