根据当前URL路由过滤JSON数据

时间:2013-06-23 19:05:17

标签: json angularjs angularjs-ng-repeat angularjs-routing

问题

我正在尝试过滤json数据,并根据页面的当前URL在Angular页面上仅显示其中的一部分。

详细

我有一个包含100个JSON对象的列表,每个对象看起来像这样:

{
  "name": "Evangeline Perreault",
  "age_1": 1,
  "total_age": 1,
  "photo_small": "img/400/001_400.jpg",
  "photo_medium": "img/800/001_800.jpg",
  "photo_large": "img/1200/001_1200.jpg",
  "photo_extralarge": "img/1600/001_1600.jpg",
  "video": 67443664,
  "id": 1,
  "quote": "test quote here and here",
  "type": 1
},

'type'属性是我想用来过滤掉我的数据子集的。考虑到这一点,我尝试设置我的URL结构,将type属性绑定到我的url。这是我的路线:

angular.module('100_Ages', ['mydirectives', 'ngResponsiveImages']).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/100_Ages/nav/:personType', {templateUrl: 'partials/person-list.html', controller: NavListCtrl}).
        otherwise({redirectTo: '/100_Ages'});
    }]);

所以,我已将路径指向我的JSON中的'type'字段,我尝试编写一个控制器将两者绑在一起。

function NavListCtrl($scope, $routeParams, $http) {
  $http.get('person.json').success(function(data) {
  angular.forEach(data, function(person) {
          if (person.type == $routeParams.personType) 
            $scope.person = person;
        });
  });
}

这是我的部分模板:

<div class="nav_outer"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>

我希望这能显示我所在的URL类型的所有匹配图像。所以,如果我在“/ 100_Ages / nav / 3”上,我希望显示来自类型为“3”的对象的所有图像(大约10张图片)。但是,它仅显示类型为“3”的最后一个对象。

所以,我尝试了ng-repeat,如此:

<div class="nav_outer" ng-repeat="person in persons"><img class="nav_img" ng-src="{{person.photo_small}}" ng-alt="{{person.name}}" /></div>

我希望能够循环显示所有匹配的图像,但这些图像根本没有显示出来。

我认为我的问题与angular.forEach有关,但我不确定如何将我的JSON类型绑定到页面的typeid。

感谢您的任何建议。

1 个答案:

答案 0 :(得分:2)

如果将每个项目推送到数组中,ng-repeat应该有效。 (另外,您指的是ng-repeat中的'人物'对象,根据提供的代码不存在)。所以,试试这个:

$http.get('person.json').success(function(data) {
    $scope.persons = [];
    angular.forEach(data, function(person) {
        if (person.type == $routeParams.personType) 
            $scope.persons.push(person);
            // or alternatively - this.push(person), with the optional 3rd param of $scope.persons (I don't really understand that, but whatever...)
    });
});

现在填充了数组,您的ng-repeat="person in persons"应该可以正常工作。

<强>更新

如果成功对象已经是一个对象数组,那么只需将范围对象设置为数组 - 无需迭代它们:

$http.get('person.json').success(function(data) {
    $scope.persons = data;    
})