【问题标题】:get count of items with some property in an array获取数组中具有某些属性的项目数
【发布时间】:2013-03-12 11:44:25
【问题描述】:

我有一个对象数组如下。

$scope.students = [{'isSelected': true},
    {'isSelected': true},
    {'isSelected': false},
    {'isSelected': true},
    {'isSelected': true},
]

如何获取将isSelected 属性设置为true 的计数项目?

更新:

问题是 $scope.students 是从 REST api 获取的,并且简单地循环 $scope.students 变量不起作用,因为该变量是 undefined 直到请求完成,所以循环代码错误地说 @ 987654326@.

我尝试使用$watch,但在这种情况下,我必须在 watch 指令下定义循环,它仅在定义 $scope.students 时有效,之后循环不作为 $scope.students 本身工作没有变化。

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    还有另一种方法可以做到这一点:AngularJS 过滤器。 你可以这样写:

    var selectedCount = $filter('filter')($scope.students, { isSelected: true }).length;
    

    【讨论】:

      【解决方案2】:

      您也可以使用 javascript 过滤方法(请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

      $scope.selectedStudentsCount = function() {
        return $scope.students.filter(function(obj){return obj.isSelected}).length;
      }
      

      【讨论】:

      • 这比 AngularJS 过滤器有什么优势(除了在没有 AngularJS 的情况下可用,这个问题不是关于)?为什么使用这个而不是 AngularJS 过滤器?
      • 没有太大的优势,只是使用标准js的替代方案。
      • +1 如果你买得起 ES6,你可能想要像酷孩子们那样使用箭头函数return $scope.students.filter((obj) => obj.isSelected).length;
      【解决方案3】:

      您可以将以下方法添加到您的控制器。您范围内的变量selectedStudentsCount 将保留所有选定学生的数量(其中isSelected 设置为true)。

      仅当students 不为空时,才会执行angular.forEach 中的

      函数计数选定用户。否则对于 empty students 变量 selectedStudentsCount 将返回 0

      $scope.selectedStudentsCount = function() {
          var count = 0;
          angular.forEach($scope.students, function(student){
              count += student.isSelected ? 1 : 0;
          });
          return count; 
      }
      

      请注意 selectedStudentsCount 是一个函数,因此必须在模板中使用 () 调用它,例如

      <h2>Total selected students: {{selectedStudentsCount()}}</h2>
      

      【讨论】:

      • 谢谢,我做了一些非常相似的事情,我没有返回计数,而是将所选学生的总数更新为函数中的 var。并通过 ng-click 使用该方法。再次感谢。
      • 不要忘记函数调用括号后的分号,即使在模板视图中!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 2021-09-26
      • 1970-01-01
      • 2015-10-06
      • 2019-02-08
      • 2017-06-19
      相关资源
      最近更新 更多