【发布时间】:2015-09-13 16:31:52
【问题描述】:
我正在尝试使用 AngularJS 创建一个简单的博客网站。我刚刚开始,所以我认为我不是最好的方法,所以欢迎任何替代建议。
我有一个带有两个博客控制器的 controller.js 文件。一个显示博客文章列表,另一个通过包含 HTML 文件显示文章内容。
controller.js
myAppControllers.controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('articles/articles.json').success(function (articles) {
$scope.articles = articles;
});
}]);
myAppControllers.controller('BlogPostCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) {
$scope.includeFile = 'articles/' + $routeParams.blogPostId + '.html';
}]);
articles.json
[
{
"id": "test-article-one",
"title": "Test Article one",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test summary"
},
{
"id": "test-article-two",
"title": "Test article two",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test for article two"
}
]
app.js
when('/blog', {
templateUrl: 'partials/blog-articles.html',
controller: 'BlogListCtrl'
}).
when('/blog/:blogPostId', {
templateUrl: 'partials/blog-post.html',
controller: 'BlogPostCtrl'
}).
blog-post.html
<ng-include src="'partials/header.html'"></ng-include>
<!-- Want to add title, author, datePosted information here... -->
<article class="content">
<ng-include src="includeFile"></ng-include>
</article>
此博客列表工作正常。当我点击一篇博文时,它也会提供 HTML 文件中的内容。但是,我希望能够重用 blog-post.html 部分视图中所选文章的 title、author 和 datePosted 属性。最好的方法是什么?我是否需要以某种方式将它们传递给控制器然后传递给视图?我真的不想将这些作为 routeParams 传递。或者我是否需要在articles.json 上执行$http.get 并遍历以找到所选文章,然后将属性值传递回视图?
感谢您的帮助。
【问题讨论】:
-
您的第一个控制器逻辑实际上应该是一个服务。 docs.angularjs.org/guide/services
标签: javascript json angularjs model-view-controller