这里是我的Plnkr:http://plnkr.co/edit/brWn6r4UvLnNY5gcFF2X?p=preview如何通过每JSON文件加载帖子浏览
比如我有一个JSON文件:
{
"info": {
"test1": "test",
"teste2": "test"
},
"posts": [
{
"name": "lorem ipsum",
"content": "sit amet lorem ipsum"
},
{
"name": "Ipsum lorem",
"content": "sit amet lorem ipsum"
},
{
"name": "lorem ipsum",
"content": "sit amet lorem ipsum"
},
{
"name": "Sit amet",
"content": "sit amet lorem ipsum"
}
]
}
在我的控制器:
var app = angular.module('plunker', ['ngRoute']);
app.controller('MainCtrl', function($scope, $http, $route, $routeParams, $filter) {
$scope.name = 'Teste';
$scope.getData = function(){
$http.get('posts.json')
.then(function(res){
$scope.posts = res.data.posts;
$scope.currentPost = $filter('filter')($scope.posts, {id: $routeParams.id})
//console.log(res.data.posts);
});
};
//setInterval($scope.getData, 1000);
$scope.getData();
});
// Routes
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'MainCtrl',
})
.when('/posts/:id', {
templateUrl: 'post.html',
controller: 'MainCtrl'
})
.otherwise({ redirectTo: '/' });
});
在我主页视图:
<div ng-repeat="post in posts">
<a href="./#/posts/{{ post.id }}">
<h3>{{ post.name }}</h3>
<h5>=> {{ post.content }}</h5>
</a>
</div>
和我的帖子视图:
<h6><a href="./#/">Back</a></h6>
<h1>POST ID: {{ currentPost.id }}</h1>
<h2>Name: {{ currentPost.name }}</h2>
<h3>Content: {{ currentPost.content }}</h3>
我在加载帖子视图时没有获取值。
谢谢!
包括每个帖子的ID和使用,在网址 – charlietfl
好的,但如何路由和范围它在我的控制器? –
不明白你在问什么。当数据中没有“id”时,请不要将新部分复制到问题中以 – charlietfl