簡體   English   中英

AngularJS過濾嵌套數組並返回父對象

[英]AngularJS filter nested array and return parent object

我最近開始擺弄AngularJS。 我正在為我的葡萄酒商店制作復選框過濾器。 一個項目看起來像這樣:

        {
     "id": 17,
     "name": "Ermelinda Freitas Reserva",
     "tag_ids": [40, 12, 56, 6, 60],
     "tag_names": ["Roasted", "Robust", "Blackberry", "Mouth-filling", "Animal"],
     "price": 29,
     "weight": "0",
     "image": "1467208469_wijn1.jpg",
     "stock": 57,
     "year": 1998,
     "special": 0,
     "color_id": 1,
     "color": "Red",
     "region_id": 25,
     "region": "Alentejo",
     "country_id": 6,
     "country": "Portugal",
     "grape_ids": [34, 35, 20],
     "grape_names": ["Castelão", "Touriga Naçional", "Cabernet Sauvignon"]
 }

我設法為該項目的國家/地區和其他非數組屬性創建了過濾器,如下所示:

for(i = 0; i< wines.length; i++){

      if($scope.countries.indexOf(wines[i].country) === -1) $scope.countries.push(wines[i].country);
    };

但是現在我正在為葡萄做一個。 我首先收集了數組中的所有唯一值,如下所示:

angular.forEach($scope.wines, function(wine){
  angular.forEach(wine.grape_names, function(grape){
    for(i = 0; i< wine.grape_names.length; i++){
      if($scope.grapes.indexOf(wine.grape_names[i]) === -1) $scope.grapes.push(wine.grape_names[i]);
    };
  });
})

因此,現在我需要檢查某個項目是否有與所選過濾器匹配的葡萄,這就是我遇到的問題:

$scope.filter.grape = {};
$scope.filterByGrape = function(wine){

  angular.forEach(wine.grape_names, function(grape){

    return $scope.filter.grape[grape] || noFilter($scope.filter.grape);
  })
};

過濾器:

<div class="col-lg-3 col-md-4 col-sm-6 " data-id="{{wine.id}}" ng-init="getQuantity(wine.id)" data-ng-repeat="wine in filteredWines =(wines | orderBy:defaultOrder | filter:filterByColor | filter:filterByCountry | filter:filterByGrape | priceRangeFilter:priceRangeSlider | yearRangeFilter:yearRangeSlider | filter:search) | start: (currentPage - 1) * itemsPerPage | limitTo:itemsPerPage">

在此處輸入圖片說明

所有幫助都非常歡迎!

問題是您只在forEach的第一次迭代中檢查grape_names,然后從那里的函數返回。

$scope.filter.grape = {};
$scope.filterByGrape = function(wine){
  var found = noFilter($scope.filter.grape);
  angular.forEach(wine.grape_names, function(grape){
     found = $scope.filter.grape[grape] || found;
  })
  return found;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM