javascript - AngularJS 加载服务然后调用 Controller 并渲染

标签 javascript synchronization angularjs

我的问题是我需要在调用 Controller 和渲染模板之前加载服务。 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;

});
​

最佳答案

您可以使用manual initialization推迟 Angular 应用程序的初始化,而不是使用 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 应用程序。

还要检查 ngCloak 指令,因为它可能是您需要的一切。

或者,当使用 ngRoute 时您可以使用 resolve 属性,因为您可以看到 @honkskillet 答案

关于javascript - AngularJS 加载服务然后调用 Controller 并渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12657389/

相关文章:

javascript - 当标签没有名称时,如何检索标签的内容?

javascript - 自动完成:在最后一项上按向下箭头键后如何专注于第一项?

javascript - 何时在 AngularJS Web 应用程序中使用 $scope?

javascript - 将用户输入 (ul) 存储在待办事项列表中,以便在重新打开程序时显示该列表

javascript - Ajax 内容可排序 jQuery portlet,加载后按 'sortOrder' 变量排序

java - 使用ReentrantLock代替synchronized来提高性能

html - Browser-Sync 不会同时同步 HTML 和 CSS 文件

javascript - 如何生成范围内的唯一数字?

javascript - 如何使用 highcharts-ng 和 angularjs 绘制多个 highcharts

javascript - AngularJS 提示没有为 jquery 定义初始化