我的问题是我需要在调用控制器和呈现模板之前加载服务。 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; });
您可以使用手动初始化来推迟angular应用的初始化,而不是使用ng-appattribute 进行自动初始化。
ng-app
// 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); }); });
callService您的函数执行AJAX调用并接受成功回调的位置在哪里,这将初始化angular app。
callService
还要检查ngCloak指令,因为它可能满足您的所有需求。
ngCloak
另外,使用ngRoute时,您可以使用resolve属性,为此,您可以看到@honkskillet答案
resolve