过滤$routeParams角度.js

filtering $routeParams in angular.js

本文关键字:js 角度 routeParams 过滤      更新时间:2023-09-26

我正在尝试过滤从 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 }
}

假设您有一条路由定义如下:

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