-1

I'm trying to list some posts from a json file then after click one, load the single post, but when I click it the data is not loaded.

I'm using the function below to handle the data

$scope.currentPost = $filter('filter')($scope.posts, {id: $routeParams.id})

Here is my Plnkr: http://plnkr.co/edit/brWn6r4UvLnNY5gcFF2X?p=preview

1 Answer 1

1

Updated Plnkr: http://plnkr.co/edit/3P2k60aPyuatjTx9raJU?p=preview

app.controller('MainCtrl', function($scope, $http, $route, $routeParams, $filter) {
  $scope.name = 'Test';

  $scope.getData = function(){
    $http.get('posts.json')
      .then(function(res){
          $scope.posts = res.data.posts;
          $scope.currentPost = $filter('filter')($scope.posts, {id: $routeParams.id});
          $scope.currentPost = $scope.currentPost[0]; // $filter apparently returns an array...
        });
  };
  // setInterval($scope.getData, 1000); // DO WE REALLY NEED IT?

  $scope.getData();

});

Alternative solution using _ (underscore) findWhere method:

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

app.controller('MainCtrl', function($scope, $http, $route, $routeParams, $filter) {
  $scope.name = 'Test';

  $scope.getData = function(){
    $http.get('posts.json')
      .then(function(res){
          $scope.posts = res.data.posts;
          // id: integer
          // $routeParams.id: string
          // when comparing integer to string _.findWhere was failing
          // always good practice to pass radix to parseInt: http://davidwalsh.name/parseint-radix
          $scope.currentPost = _.findWhere($scope.posts,  {id: parseInt($routeParams.id, 10)});
        });
  };
  // setInterval($scope.getData, 1000); // DO WE REALLY NEED IT?

  $scope.getData();

});

Plnkr: http://plnkr.co/edit/N7UeaOuoNIoQgzQfrkY3?p=preview

In my code I usually use _ but now I've learnt something new - I can use $filter too!

Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thanks! But apparently there is a delay with a previous data loaded. There is some way to clear the previous data before load the view?
"there is a delay"... I think it might be related to making GET request to post.html (loading partials over the wire)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.