【问题标题】:What is the best way to get the length of all true values for a $scope object in angularjs?在 angularjs 中获取 $scope 对象的所有真值长度的最佳方法是什么?
【发布时间】:2014-04-10 08:47:48
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

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

    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);
    

    在 Angular 中:

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

    【讨论】:

    • 在哪里定义函数?在控制器或过滤器中?
    • 如何将其移至自定义过滤器以便重复使用该功能?
    • 那是另一个问题,但给我你的电子邮件,我会给你一个例子。
    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2021-02-22
    相关资源
    最近更新 更多