AngularJS 加载服务然后调用控制器并渲染 [英] AngularJS load service then call controller and render
问题描述
我的问题是我需要在调用控制器和渲染模板之前加载服务.http://jsfiddle.net/g75XQ/2/
HTML:
<h3>在用户加载之前不要渲染它</h3>{{用户}}
JavaScript:
angular.module('app', []).工厂('用户',功能($超时,$ q){无功用户 = {};$timeout(function(){//模拟一个请求用户名 = "乔西";},1000);返回用户;}).控制器('root',功能($范围,用户){alert("用户加载前不要提醒");$scope.user = 用户;});
您可以使用 手动初始化,而不是使用 ng-app
属性自动初始化.
//定义一些注入 `$window` 并从中读取数据的服务angular.service('myService', ['$window', ($window) =>({获取数据(){返回 $window.myData;}}))const callService = (cb) =>{$.ajax(...).success((data)=>{window.myData = 数据;CB(数据)})}//初始化角度应用angular.element(document).ready(function() {callService(函数(数据){做某事(数据);angular.bootstrap(文档);});});
其中 callService
是您执行 AJAX 调用并接受成功回调的函数,它将初始化 angular 应用程序.
还要检查 ngCloak
指令,因为它可能是您需要的一切.
或者,当使用 ngRoute 时,您可以使用 resolve
属性,为此你可以看到@honkskilet 的回答
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;
});
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
这篇关于AngularJS 加载服务然后调用控制器并渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!