我试图从json文件中列出一些帖子然后点击一个后加载单个帖子,但是当我点击它时数据没有加载。
我使用以下功能处理数据
$scope.currentPost = $filter('filter')($scope.posts, {id: $routeParams.id})
这是我的Plnkr:http://plnkr.co/edit/brWn6r4UvLnNY5gcFF2X?p=preview
答案 0 :(得分: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
!