2017-09-02 34 views
1

我有一些數據在JSON格式,並希望在我的HTML頁面查看它,我用$ routeParams爲此,但數據不能從JSON文件中獲取。 我創造了這樣一個控制器:

angular.module('app.controllers', [ 
    'app.directives' 
]) 
    .controller('PostController', ['$scope', '$http', function ($scope, $http){ 
     $http.get('data/posts.json').then(function (data) { 
      $scope.posts = data.data; 
     }); 
    }]) 
    .controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { 
     $http.get('data/posts.json').then(function (data){ 
      $scope.post = data[$routeParams.id]; 
     }); 
    }]); 

而且配置:

angular.module('app', [ 
    'ngRoute', 
    'app.controllers' 
]) 
    .config(['$routeProvider', function($routeProvider) { 
     $routeProvider.when('/',{ 
      templateUrl : 'views/post.html', 
      controller : 'PostController' 
     }).when('/post/:id', { 
      templateUrl: 'views/singlepost.html', 
      controller: 'SinglePostController' 
     }).otherwise({ 
      redirectTo : '/' 
     }); 
    }]); 

當數據需要抓取的HTML頁面:

<h1>{{post.title}}</h1> 
<p>{{post.content}}</p> 

幫助!

+0

你通過在HTML中的數據循環之前? – user2085143

+0

是循環瀏覽數據! –

+0

你會幫忙嗎? –

回答

1

您可能需要申報範圍的變量,你做http.get即

.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { 
     $scope.post = {}; 
     $http.get('data/posts.json').then(function (data){ 
      $scope.post = data.data[$routeParams.id]; 
     });