unable to view data redirected using $routeParams in angular

48 views Asked by At

i have some data in the json format and want to view it in my html page, i used $routeParams for this, but the data cant be fetched from the json file. I created a controller like this:

    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];
        });
    }]);

and the configuration is:

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 : '/'
        });
    }]);

the html page where the data has to be fetched is:

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

Help!

1

There are 1 answers

0
user2085143 On BEST ANSWER

You might need to declare the scope variable before you do http.get i.e.

.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];
        });