2012-06-23 91 views
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 } 
} 

回答

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; 
     }); 
    }); 
} 
相關問題