如何创建自定义过滤器以在Angular 1.3.6中搜索嵌套数组?

时间:2015-02-06 21:19:45

标签: javascript arrays angularjs

我有这个数组sports,json看起来像:

 [
  {
    "id": 26,
    "name": "LIVE Betting",
    "priority": 0,
    "leagues": []
  },
  {
    "id": 8,
    "name": "NBA",
    "priority": 3,
    "leagues": [
      {
        "id": 5932,
        "parent": 1000,
        "name": "NBA",
        "sport": {
          "id": 8,
          "name": "NBA"
        },
        "lineType": "G",
        "priority": [
          1,
          3
        ],
        "part": "0"
      }
    ]
  },
  {
    "id": 24,
    "name": "College Basketball",
    "priority": 4,
    "leagues": [
      {
        "id": 2599,
        "parent": 1000,
        "name": "NCAA BASKETBALL",
        "sport": {
          "id": 24,
          "name": "College Basketball"
        },
        "lineType": "G",
        "priority": [
          0,
          4
        ],
        "part": "0"
      },
      {
        "id": 2631,
        "parent": 1000,
        "name": "NCAA BASKETBALL ADDED GAMES",
        "sport": {
          "id": 24,
          "name": "College Basketball"
        },
        "lineType": "G",
        "priority": [
          1,
          4
        ],
        "part": "0"
      },
      ...

在该数组中,您可以看到名为"leagues": [{...}]的其他数组,其中包含Object,我的过滤器正在通过顶部数组sports进行搜索,但是一旦我尝试通过"name"数组中的leagues,然后我的应用会显示过滤器为空的消息。

我刚刚意识到这种情况正在发生,因为我使用的是Angular的版本1.3.6,但是在Ionic人员将其升级到1.3.8之前我无法更改它,我做了{{3}使用版本1.3.8并且它可以正常运行,但是如果您将同一个Plnkr上的版本更改为1.3.6,则会自动停止搜索leagues.name并且仅适用于sport.name,和this Plnkr,在两个Plnkrs上尝试搜索Greece,在第一个版本中使用版本1.3.8,但在版本1.3.6中,只有消息no sports to show出现

<input type="search" ng-model="query">

<div ng-repeat="sport in sportsFilter = (sports | filter:query)">
        <!--this array works fine-->
        <strong>{{sport.name}}</strong>
      </div>
      <div ng-repeat="league in sport.leagues">
        <!--this one not works at all-->
        {{league.name}}
      </div>
</div>

我已经尝试了所有方式,resolve,不同型号等等,实际上我只是意识到我需要一个自定义过滤器,所以我希望你能帮我一臂之力我不知道从哪里开始。

还是有更简单的方法吗?

2 个答案:

答案 0 :(得分:1)

<div ng-app="myApp">
  <div ng-controller="TestController">
    <input type="search" placeholder="Search" ng-model="query">

    <div role="alert" ng-show="sportfilter.length==0">No sports to show</div>

    <div ng-repeat="sport in sportfilter=(sports  | filter:matchNameDeep(query))" ng-show="sport.leagues.length">
      <div>
        <strong>{{sport.name}}</strong>
      </div>

      <div class="item item-button-right" ng-repeat="league in sport.leagues" on-tap="goToLines(league)">
        {{league.name}}
      </div>
    </div>
  </div>
  </div>


$scope.matchNameDeep = function(query) {
  return function(sport) {
    return !query || sport.name.match(new RegExp(query, "ig")) || sport.leagues.some(function(element, index, array) {
    return element.name.match(new RegExp(query, "ig"))
    });
  }
};

在这里看到它使用角度1.3.6 http://plnkr.co/edit/0w9PYbDsOz0mHBdVldZt?p=preview

答案 1 :(得分:0)

您可以将https://github.com/marklagendijk/lodash-deep用于此类事情。