2017-04-19 73 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

相关问题