将routeParam与ID属性匹配并显示相关对象

时间:2014-09-11 19:37:58

标签: javascript angularjs url-routing

我有一个如下所示的JSON文件:

[
  {
    "id":"112",
    "title":"Title here",
    "date":"1234567890"
  }
  {
    "id":"113",
    "title":"Title here",
    "date":"1234567890"
  }
...
]

我有两个部分/观点。列出所有对象的列表视图,以及由" ng-click"触发的详细信息页面。作为参数" id"属性。

我的路线有效,细节部分。

我构建了一个服务来执行请求和两个控制器:

var chatServices = angular.module('itemServices', ['ngResource']);

chatServices.factory('Item',['$resource',
  function($resource){
    return $resource('data.json', {}, {
      query: {method:'GET', params:{}, isArray:true}
    });
  }
]);

  chatListApp.controller('ItemsController', ['$scope', 'Item', "$location",
    function ($scope, Item, $location) {
      $scope.items = Item.query();
      $scope.detailPage = function (hash) { 
        $location.path(hash);
      }
    }]);

    chatListApp.controller('DetailController', ['$scope', '$routeParams', 'Item',
      function($scope, $routeParams, Item) {
        $scope.data = Item.query();
        $scope.itemID = $routeParams.itemID;
        }
    ]);

所以,我有一个像http://domain.foo/112这样的网址,我想让它显示我的JSON文件的第一个对象(或者数据数组,如果你愿意的话)。 当我在视图中尝试{{data [0]}}时,我得到了对象,那么我该如何添加一些逻辑并获取ID值等于$ scope.itemID的对象(如在routeParams中?

1 个答案:

答案 0 :(得分:0)

你有id,并且你有数据,所以你可以循环获取项目的数据:

chatListApp.controller('DetailController', ['$scope', '$routeParams', 'Item',
  function($scope, $routeParams, Item) {
    $scope.itemID = $routeParams.itemID;
    $scope.data = Item.query(function() {
      for (var i = 0; i < $scope.data.length; i++) {
        if ($scope.data[i].id === $scope.itemID) {
          $scope.item = $scope.data[i];
          break;
        }
      } 
    });
  }
]);

然后在您的视图中使用item

更新:使用angular.forEach替换循环,如下所示:

angular.forEach($scope.data, function(item) {
  if (item.id === $scope.itemID) {
    $scope.item = item;
  }
});