【问题标题】:Angular JS filter an overview based on array of categoriesAngular JS 根据类别数组过滤概览
【发布时间】:2016-07-27 23:51:02
【问题描述】:

我要做的是创建一个可以根据嵌套在 JSON 对象数组中的类别进行过滤的概览。

我要创建概览的项目的 JSON 如下所示:

{
  id: 1,
  title: "title",
  content: "content",
  categories: [{
      title: "cat1",
      descripton: "desc"
  },
  {
      title: "cat2",
      descripton: "desc"
  }]
},
{
  id: 2,
  title: "title",
  content: "content",
  categories: [{
      title: "cat3",
      descripton: "desc"
  },
  {
      title: "cat4",
      descripton: "desc"
  }]
}

HTML 看起来像这样:

<select ng-model="catselect">
  <option>cat1</option>
  <option>cat2</option>
  <option>cat3</option>
  <option>cat4</option>
</select>
<ul>
  <li ng-repeat="item in array | filter: {ARRAY OF CATEGORIES: catselect}">

  </li>
</ul>

目前我不知道如何让它工作。 (我认为)最明显的解决方案应该是 filter: {categories.title: catselect} 之类的东西,但显然不是。据我所知,Stackoverflow 上没有其他问题可以解决这个问题。我很想看看是否有人可以帮助我。

【问题讨论】:

    标签: html angularjs json


    【解决方案1】:

    你可以试试这个看看它是否有效?我没有实际测试过。

    filter: { categories: { title: catselect } }
    

    【讨论】:

    • 感谢您的麻烦!这个解决方案虽然不起作用:(
    • 尝试我的答案的变体,例如:过滤器:{类别:{标题:catselect}}或其他,当我的对象中有一个对象时,这实际上对我有用,没有尝试在一个对象..
    • 这确实有效! :) 您可以编辑您的答案以便我接受吗?
    • 编辑了答案 =)
    【解决方案2】:

    自定义过滤器将起作用

    angular.module("app", [])
      .controller("test", function($scope) {
    
        $scope.array = [{
          id: 1,
          title: "title",
          content: "content",
          categories: [{
            title: "cat1",
            descripton: "desc"
          }, {
            title: "cat2",
            descripton: "desc"
          }]
        }, {
          id: 2,
          title: "title2",
          content: "content",
          categories: [{
            title: "cat3",
            descripton: "desc"
          }, {
            title: "cat4",
            descripton: "desc"
          }]
        }]
      })
      .filter("filterByCat", function() {
        return function(input, catselect) {
          if (catselect != undefined) {
            var f = []
            angular.forEach(input, function(el) {
              if ((el.categories.filter(function(cat) {
                return cat.title == catselect
              })).length > 0) f.push(el);
            })
            return f;
          } else {
            return input;
          }
        }
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="test">
      <select ng-model="catselect">
        <option>cat1</option>
        <option>cat2</option>
        <option>cat3</option>
        <option>cat4</option>
      </select>
      <ul>
        <li ng-repeat="item in array | filterByCat:catselect">{{item.title}}</li>
      </ul>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多