Sunday 27 March 2016

javascript - 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:




Do not render this before user has loaded


{{user}}





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.



// define some service that has `$window` injected and read your data from it
angular.service('myService', ['$window', ($window) =>({
getData() {
return $window.myData;
}
}))


const callService = (cb) => {
$.ajax(...).success((data)=>{
window.myData = data;
cb(data)
})
}

// init angular app
angular.element(document).ready(function() {
callService(function (data) {

doSomething(data);
angular.bootstrap(document);
});
});


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



Also check ngCloak directive, since it maybe everything you need.




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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...