在angularjs中获取$scope对象所有真值长度的最佳方法是什么

What is the best way to get the length of all true values for a $scope object in angularjs?

本文关键字:最佳 是什么 方法 获取 angularjs scope 对象      更新时间:2023-09-26

我有这个对象,想获得所有键的长度,其中值为"true",然后在HTML文件中显示长度:

$scope.foobar = [
  {"a": false},
  {"b": false},
  {"c": true},
  {"d": true}
]

经过一些研究,我发现我可以使用自定义过滤器:

{{ (foobar | trueValues).length }}
  1. 自定义筛选器应该是什么样子
  2. 这是最好的方式吗

使用Array.prototype.filter()并获取每个元素的第一个属性

function isTrue(obj) {
  return obj[Object.keys(obj)[0]] == true;
}
var trueArray= $scope.foobar.filter(isTrue);
console.log(trueArray.length);

或者您可以包含回调函数而不声明它为

    var len = $scope.foobar.filter(function(obj) {
        return  obj[Object.keys(obj)[0]] == true;
    }).length;
    console.log(len);

角度:

$scope.trueLen = function() {
    return $scope.foobar.filter(function(obj) {
        return  obj[Object.keys(obj)[0]] == true;
    }).length;
}