2017-04-19 47 views
0

我試圖通過一組來自不同對象的複選框來過濾我的ng-repeat。對象1擁有我的類別和對象2擁有我所有的文章AngularJS使用一個對象作爲另一個過濾器

分類對象將變成複選框。這些複選框應該用作文章的過濾器。一篇文章可以有多個類別。

$ scope.categories:

[ 
    { 
    "id": "1", 
    "title": "Blog" 
    }, 
    { 
    "id": "2", 
    "title": "News" 
    } 
] 

$ scope.articles:

[ 
    { 
    "id": "1", 
    "title": "Whats going on", 
    "categories":{ 
    "results" : [1,2,3] 
    } 
    }, 
    { 
    "id": "2", 
    "title": "Trump!", 
    "categories":{ 
    "results" : [3] 
    } 
    } 
] 

複選框:

<div class="filter-pills" ng-repeat="cat in categories"> 
    <input type="checkbox" ng-model="filter[cat.Id]" ng-checked="cat.checked"/>{{cat.Title}}       
</div> 

NG-重複:

<div class="col-lg-3 col-md-4" ng-repeat="item in articlesFinal"></div> 

我已經嘗試了不同的解決方案,如ng-change當我更新我的filter陣列和比較,在ng-repeat使用的對象。

我似乎無法找出這一個。有什麼建議麼?

回答

0

試試這個

<div class="filter-pills" ng-repeat="cat in categories"> 
     <input type="checkbox" ng-model="cat.checked"/>{{cat.title}} 
</div> 
<div class="col-lg-3 col-md-4" ng-repeat="item in articles | filter: catFilter">{{item.title}}</div> 

和控制器

$scope.catFilter = function (article) { 
     var checkedCats = vm.categories.filter(function (cat) { 
      return cat.checked; 
     }); 
     // no filter, show all 
     if(checkedCats.length == 0) return true; 

     for(var i = 0; i < checkedCats.length; i++){ 
      var id = checkedCats[i].id; 
      if(article.categories.results.indexOf(id) >= 0){ 
       return true; 
      } 
     } 
     // no match, then false 
     return false 
    }; 

還要注意類別ID應該是整數,不串

$scope.categories = [ 
      { 
       "id": 1, // integer 
       "title": "Blog" 
      }, 
      { 
       "id": 2, 
       "title": "News" 
      } 
     ]; 
     $scope.articles = [ 
      { 
       "id": "1", 
       "title": "Whats going on", 
       "categories":{ 
        "results" : [1,2,3] // integer 
       } 
      }, 
      { 
       "id": "2", 
       "title": "Trump!", 
       "categories":{ 
        "results" : [3] 
       } 
      } 
     ]; 
+0

偉大的作品!謝謝! – TietjeDK

相關問題