回答

1

更新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(); 

}); 

替代解决方案(下划线)findWhere方法:

<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

在我的代码我通常使用_但现在我已经学到新的东西 - 我可以使用$filter呢!

+0

无法正常工作=( –

+0

对不起...正在工作... 1分钟...现在正在工作.. –

+0

它的工作原理!谢谢!但显然有一个延迟与以前的数据加载。是否可以在加载视图之前清除以前的数据? –