使用ng-repeat中的制表符进行复杂排序?

时间:2017-02-20 16:26:16

标签: angularjs

我有以下JSON对象:

      $scope.projects = [
  {
    "_id": "58ab1cb6edf5430e9014e2bc",
    "name": "Project 1",
    "issues": [
      {
        "status": 0,
        "name": "Hart Cummings"
      },
      {
        "status": 1,
        "name": "Kinney Leach"
      },
      {
        "status": 2,
        "name": "Blake Mclaughlin"
      }
    ]
  },

  {
    "_id": "58ab1cb6d87456482e0eec4a",
    "name": "Project 2",
    "issues": [
      {
        "status": 0,
        "name": "Vargas Gordon"
      },
      {
        "status": 1,
        "name": "Bobbie Church"
      },
      {
        "status": 2,
        "name": "Pennington Fry"
      }
    ]
  },

  {
    "_id": "58ab1cb6d87456482e0eec4a",
    "name": "Project 3",
    "issues": [
      {
        "status": 0,
        "name": "WWWWW"
      },
      {
        "status": 1,
        "name": "SFSF"
      },
      {
        "status": 2,
        "name": "Pennington Fry"
      }
    ]
  }
];

我使用ng-repeat在模板中显示此对象:

    <div ng-app="app">
<div ng-controller="TodoListController">

<div ng-repeat="project in projects">
<br>
   <br>
 <div><b> {{project.name}}</b></div>

   <div class="tabs">
      <div style="display:inline" ng-click="sort(1, $index);">Active</div> |
      <div style="display:inline" ng-click="sort(0, $index);">Deactivated</div> 
   </div>

   _____________________________________
   <div ng-repeat="issue in project.issues | filter: (filterObject.index | filterObject.status)">
      <div>{{issue.name}}</div>
    </div>
</div>


</div>
</div>

所以,你可以看到我有两个嵌套的ng-repeat

问题是:

当我点击任意标签并调用方法sort()时,我需要按issue in project.issues字段对status进行排序。

这是我想要达到的真实样本。

https://jsfiddle.net/at6kw67g/

问题在于此代码:

<div ng-repeat="issue in project.issues | filter:filterObject.index : {status : filterObject.status}">

1 个答案:

答案 0 :(得分:1)

由于链接应该对特定项目的问题进行排序,因此您应该将项目作为参数传递给sort()函数。

JavaScript数组有一个sort()方法,所以只需使用它。

由于一个链接应按照ascanding顺序排序问题,另一个链接按降序排序,因此您还应将此信息传递给sort()函数。

所以归结为

  $scope.sortIssuesByStatus = function(project, descending) {
    project.issues.sort(function(issue1, issue2) {
      var result = issue1.status - issue2.status;
      if (descending) {
        result = -result;
      }
      return result;
    });
  }

<div ng-repeat="project in projects">
   <div class="tabs">
      <button ng-click="sortIssuesByStatus(project, true)">Active</button> 
      <button ng-click="sortIssuesByStatus(project, false)">Deactivated</button> 
   </div>
   <div ng-repeat="issue in project.issues">
      <div>{{issue.name}} - {{ issue.status }}</div>
    </div>
</div>

此处a plunkr正在实施它。