2

我正在尝试过滤从 json 文件返回的数据的 $routeParams。下面是我的代码:

function PostDetailController($scope, $routeParams, $http) {
    $http.get('json/posts.json').success(function(data){
        $scope.photo = data;
    });
}

如何过滤给定 url 的 id?下面是我的 json 的样子

{
    "id": 1,
    "name": "details1",
    "title": "Test Title",
    "description": "Sample Description",
    "image": "img/1.jpg",
    "tags": ["photo", "internet"],
    "user": "hilarl",
    "comments": ["sample comment"],
    "likes": 23,
    "dislikes": 100,
    "resolution": { "x": 150, "y": 58 }
},
{
    "id": 2,
    "name": "details2",
    "title": "Test Title",
    "description": "Sample Description",
    "image": "img/2.jpg",
    "tags": ["photo", "internet"],
    "user": "hilarl",
    "comments": ["sample comment"],
    "likes": 23,
    "dislikes": 100,
    "resolution": { "x": 150, "y": 58 }
}
4

1 回答 1

9

假设您有这样定义的路线:

$routeProvider.when('/post/:postId', {...})

然后在您的控制器中,您可以从 $routeParams 检索 id:

function PostDetailController($scope, $routeParams, $http) {
    $http.get('json/posts.json').success(function(data){
        angular.forEach(data, function(item) {
          if (item.id == $routeParams.postId) 
            $scope.photo = item;
        });
    });
}
于 2012-06-23T15:59:42.500 回答