【问题标题】:Get the length based on specific condition using Angular.js使用 Angular.js 根据特定条件获取长度
【发布时间】:2014-11-06 21:39:14
【问题描述】:

我们有以下使用 Angular.js 的 HTML 代码,

<div ng-if="$scope.IsResult == false">
  <label style="font-weight: bold;"> Count : {{student.length }}</label>
</div>

这里的 student 是返回的 JSON 数组,包含一些 student.Active=false 的记录。

目前它显示所有学生人数。 我们只需要显示活跃学生的长度,即 student.Active=true。如何在 Angular.js 中实现这一点。

请指教。

【问题讨论】:

  • 我创建了一个library,它为您提供了一些简单的函数来操作数组。您可以使用.Count({ active: true}) 来查找有多少项活动设置为 true!
  • @No1_Melman Underscore.js 是另一个很棒的库,它有很多这样的功能,就像 Javascript 的 Linq,非常酷
  • @JMK 是的,我的库的目的是允许用户使用底层 api 添加他们想要的任何内容。但在足迹和代码方面也要简约。还有很多其他的库可以解决这个问题。我刚刚为这种确切情况创建了我的库

标签: html angularjs


【解决方案1】:

你最好在你的控制器中放置一个函数来计算这个并从你的视图中调用它。

所以在你的控制器中:

$scope.countInactiveStudents = function(student){
    var count = 0;
    for(var i = 0; i < student.length; i++){
        if(!student[i].Active){
            count++;
        }
    }
    return count;
}

在你看来:

<label style="font-weight: bold;"> Count : {{countInactiveStudents(student) }}</label>

【讨论】:

  • 你应该把 "i++" 换成 "count++" :)
  • 哇,它工作了谢谢。是的,它是 count++,然后它起作用了。
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多