AngularJS使用对象数组

时间:2016-11-20 04:03:19

标签: angularjs arrays object filter compare

我试图通过idSubject用我自己的对象过滤嵌套的对象数组。但我没有得到正确的结果。

我有文章(有主题) 和一系列对象(我想要过滤文章的主题)

数据如下所示:

enter image description here

enter image description here

所以我试图按其主题过滤文章数组。

我尝试了以下内容:

<div class="panel panel-default"
                     ng-repeat="searchArticle in searchArticles | filter: {subjects: filterSubjects} as articleSearchResult">

所以filterSubjects是第二个截图,SearchArticles是第一个截图。

没有太多运气。

希望你能提供帮助,如果事情还不清楚,请告诉我。

1 个答案:

答案 0 :(得分:1)

此自定义过滤器可以为您提供帮助。

示例:http://plnkr.co/edit/jMizCLxPH6DtDA5wL15Q?p=preview

HTML:

<body ng-app="myApp">
  <div ng-controller="MainCtrl">
<h2>Select Subjects</h2>
    <div ng-repeat="subject in subjects">
      <label>
        <input type="checkbox" ng-model="filterSubjects[subject.id]" ng-true-value="'{{subject.id}}'" ng-false-value="''">{{subject.name}}</label>
    </div>

    <h2>Filtered Articles</h2>

    <div ng-repeat="searchArticle in searchArticles | subjectFilter:filterSubjects">{{searchArticle.name}}</div>
  </div>
</body>

JS:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.searchArticles = [{
    "name": "Article1",
    "sid": "1"
  }, {
    "name": "Article2",
    "sid": "1"
  }, {
    "name": "Article3",
    "sid": "2"
  }];
  $scope.subjects = [{
    "name": "Subject1",
    "id": "1"
  }, {
    "name": "Subject2",
    "id": "2"
  }];
  $scope.filterSubjects = [];

});

app.filter('subjectFilter', function() {
  return function(articles, filterSubjects) {
    filtered = articles.filter(function(e){return filterSubjects.indexOf(e.sid) >= 0},filterSubjects);
    return filtered;
  }
});

如果您想根据对象进行过滤:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.searchArticles = [{
    "name": "Article1",
    "sid": "1"
  }, {
    "name": "Article2",
    "sid": "1"
  }, {
    "name": "Article3",
    "sid": "2"
  }];
  $scope.subjects = [{
    "name": "Subject1",
    "id": "1"
  }, {
    "name": "Subject2",
    "id": "2"
  }];
  $scope.filterSubjects = [{
    "name": "Subject1",
    "id": "1"
  }, {
    "name": "Subject1",
    "id": "2"
  }];

});

app.filter('subjectFilter', function() {
  return function(articles, filterSubjects) {
    var sFiltered = [];
    for (var i = 0; i < filterSubjects.length; i++) {
      sFiltered.push(filterSubjects[i].id);
    }
    var filtered = articles.filter(function(e) {
      return sFiltered.indexOf(e.sid) >= 0;
    }, sFiltered);
    return filtered;
  }
});