我有导航栏、主页内容和页脚。在所有这些中,我需要显示相同的数据,但它们位于不同的 Controller 中。 我尝试在运行阶段执行一个请求,并将数据插入到服务中并共享该数据。但问题是由于 promise 模式而导致的延迟。 我试图避免将其放入 rootScope 中。 有人有更好的主意吗?
运行阶段的示例:
PostsService.getPosts().then(function(data) {
PostsService.posts = res.data;
}
the controllers:
//home
$stateProvider
.state('home', {
url: "/",
controller:HomeController,
templateUrl: "views/home/index.html"
});
// nav controller
$scope.posts= PostsService.posts;
console.log(PostsService.posts) // is an empty array
the html:
//home view
//return data
<div ng-repeat="posts in posts">
<p>{{post.body}}</p>
</div>
//nav view is not return data
<section ng-controller="NavController">
<div ng-repeat="posts in posts">
<p>{{post.body}}</p>
</div>
</section>
//footer
<section ng-controller="FooterController">
<div ng-repeat="posts in posts">
<p>{{post.body}}</p>
</div>
</section>
最佳答案
如果您使用 ui-router
,您可以将加载逻辑放入状态的 resolve
(而不是通用的 run
函数中) )等待状态解析,直到加载完成。然后,您可以将解析后的本地服务注入(inject)到状态 Controller 中(您甚至可以在子状态中执行此操作)。
$stateProvider.state('home', {
// ...
resolve: {
posts: ['PostsService', function (PostsService) {
return PostsService.getPosts();
}]
},
controller: ['$scope', 'posts', function ($scope, posts) {
$scope.posts = posts;
}]
});
关于javascript - Angular 一次请求页面上的三个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27083037/