Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a promise in a Run block in AngularJS?

Tags:

angularjs

I really need some data to be loaded before bootstrapping angular. For this reason I've created a run block/ Within this run block I call a method on a service which load some data from the server. Since this is a async call, JavaScript gets further with execution, which results in some undefined objects in my app.

I am working with routes, but it is not an option to work with the resolve property.

Could someone provide a solution on how to wait for a promise to be ready in the run block?

EDIT:

Thanks to the given answers, I have solved it by manually bootstrapping angular:

$(document).ready(function () {     $.ajax('/Data/GetDropdownData', {type:'POST'}).done(function (response) {         app.run(['ListService',  function (ListService) {             ListService.setData(response);         }])          angular.bootstrap(document, ["sma"]);     }) }) 
like image 447
Martijn Avatar asked Feb 11 '14 09:02

Martijn


2 Answers

You may want to look at this SO question - it shows how to initialize an AngularJS service with asynchronous data.

Here is a plunkr example from that question showing the use of AngularJS services like $http to load the configuration and then do further initialization.

This answer has a great explanation and shows an example of waiting for the DOM to load like this (plunkr example from that answer is here) :

angular.element(document).ready(function() {   angular.bootstrap(document); }); 
like image 82
SnapShot Avatar answered Sep 17 '22 16:09

SnapShot


As I commented would put it here

You may try manual bootstrap

<script>     angular.element(document).ready(function() {       angular.bootstrap(document);     }); </script> 

Of cause in this case you cannot use controllers and angular way of getting data. I think you would have to load your data by jQuery, bootstrap your angular in jquery callback and then init your scope variable with data you got from jquery.

like image 39
Fedor Skrynnikov Avatar answered Sep 19 '22 16:09

Fedor Skrynnikov