【问题标题】:Angularjs: Ng-repeat and unique filter in arrayAngularjs:数组中的 Ng-repeat 和唯一过滤器
【发布时间】:2016-02-28 23:11:18
【问题描述】:

我有一组这样的数据

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

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

<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"]

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

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

【问题讨论】:

标签: angularjs angularjs-ng-repeat angularjs-filter


【解决方案1】:

我真的建议您使用库 LodashUnderscore 来解决此类问题。学习掌握这些对我帮助很大!

当然,您可以使用其中之一创建自己的角度滤镜。你想使用的方法是 union:

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

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

【讨论】:

  • 我不知道我可以轻松创建自己的自定义过滤器。这让我很开心:)
【解决方案2】:

如果实际要求是:

...获取所有主题的列表,无需重复。

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

$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>

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

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

但它没有提供所需的输出。

如果你能告诉我们想要的输出是什么,那将会很有帮助!

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

【讨论】:

  • 我编辑了这个问题。您的解决方案的输出是正确的,但我不想为此设置单独的范围,因为稍后我无法通过 ng-model 将其绑定到另一个范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 2016-07-31
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 2013-05-09
  • 2020-05-28
相关资源
最近更新 更多