Jossi Jossi - 3 months ago 9
AngularJS Question

AngularJS load service then call controller and render

My problem is that i need a service loaded before the controller get called and the template get rendered.
http://jsfiddle.net/g75XQ/2/

Html:

<div ng-app="app" ng-controller="root">
<h3>Do not render this before user has loaded</h3>
{{user}}
</div>



JavaScript:

angular.module('app', []).
factory('user',function($timeout,$q){
var user = {};
$timeout(function(){//Simulate a request
user.name = "Jossi";
},1000);
return user;
}).
controller('root',function($scope,user){

alert("Do not alert before user has loaded");
$scope.user = user;

});




Answer

You can defer init of angular app using manual initialization, instead of auto init with ng-app attribute.

angular.element(document).ready(function() {
       callService(function () {
          angular.bootstrap(document);
       });
   });

where callService is your function performing ajax call and accepting success callback, which will init angular app.

Alternatively, when using ngRoute you can use resolve property, for that you can see @honkskillet answer

Comments