Angularjs: Ng-repeat and unique filter in array

Angularjs: Ng-repeat and unique filter in array

我有这样一组数据

$scope.students = [
   { name:"John", courses:["Math", "Physics", "Chemistry"] },
   { name:"Paul", courses:["Economics", "Math", "Sociology"] }
]

我想要一种使用 angular-filter 进行过滤的方法,这样我就可以获得所有主题的列表而无需重复。 我一直在尝试使用独特的过滤器,但我无法让它工作,因为我尝试像

一样迭代
<ul ng-repeat="student in students">
   <li ng-repeat="x in student.courses | unique:courses"></li>
       {{x}}
</ul>

我希望第一个 ng-repeat 的输出是这样的数组:

["Math", "Physics", "Chemistry", "Economics", "Sociology"]

所以我可以在第二个中遍历它。

我已经通过只用所需数组创建一个新范围来实现这一点,但是我无法正确绑定它,所以我想通过过滤来实现它。提前致谢。

我强烈建议您使用库 Lodash or Underscore 来解决此类问题。学习掌握这些对我帮助很大!

当然,您可以使用其中之一创建自己的 angular 过滤器。您要使用的方法是联合:

_.union(_.flatten(_($scope.students).pluck("courses")))

我使用 pluck 从 studens 对象中取出课程数组,然后我将结果展平(以摆脱它嵌套的数组),然后我使用 union 只获取每个主题一次。

如果实际要求是:

...get a list of all the subjects without repetition.

然后我会为主题创建一个单独的数组:

$scope.courses = [];

// There are many ways to do skin this cat... (prograde does have a point!)
$scope.students.forEach(function(student) {
  student.courses.forEach(function(course) {
    if ( $scope.courses.indexOf(course) === -1 ) {
      $scope.courses.push(course);
    }
  })
});

HTML

<ul>
  <li ng-repeat="course in courses">
    {{ course }}
  </li>
</ul>

如果学生发生变化,我会重新创建课程数组。

但听起来好像您正在尝试做其他事情。

But it doesn't give the desired output.

如果您告诉我们所需的输出是什么,将会有所帮助!

http://plnkr.co/edit/bZNjIEFznvuyTU3zxAp1?p=preview