繁体   English   中英

(Angular.js)如何通过过滤器计算数组中有多少项?

[英](Angular.js) How to count how many item there are in an array by filter?

在有角JS中,我有一个变量来跟踪人及其年龄

$scope.people = [
    {
        name: "Lucy",
        age: "18"
    }, {
        name: "Michael",
        age: "24"
    }, {
        name: "Lisa",
        age: "46"
    }
];

用户可以通过一个简单的表单添加更多人:

<input ng-model="newPerson.name">
<input ng-model="newPerson.age">
<button ng-click="addNewPerson()">Add</button>

在页面底部,我想要一个简单的饼图,显示按年龄段划分的人口,例如(> 18、18-25、26-35、36-45、45 <)。 为此,我需要能够按年龄过滤$scope.people ,获取每个组的数量。

我知道我可以使用普通的javascript遍历整个数组,获取每个年龄段的计数。 每当添加一个新人时,只需增加该特定组中的人数即可,但是我想知道是否有更有效且棱角分明的方式来做到这一点?

您可以使用像lodash这样的库: _($scope.people).filter(x => x.age > 18 && x.age <= 25).count()

或者,如果您已经在ng-repeat中使用过滤列表,则可以将其分配为变量并获取长度,例如:

<ul>
    <li ng-repeat="item in people | filter:filterFunction as results"></li>
</ul>
<p>{{results.length}}</p>

function filterFunction(item) {
    return item.age > 18 && item.age <= 25;
}

这是使用Array.Prototype.filterArray.Prototype.reduce实现此目的的一种方法。 请注意,该过滤器应用于$scope.ageBrackets ,其中包含由forEach循环准备的预处理数据。 这对于小范围的值(例如人的年龄)非常有效。 如果您不使用ng-repeat并且不想多次过滤数据,则这是一种选择。

 angular.module('ageBracketApp', ['ageBracketApp.controllers']); angular.module('ageBracketApp.controllers', []).controller('ageBracketController', ['$scope', function($scope) { $scope.ageBrackets = []; $scope.people = [{ name: "Lucy", age: "18" }, { name: "Michael", age: "24" }, { name: "Lisa", age: "46" }]; angular.forEach($scope.people, function(value, key) { $scope.ageBrackets[value.age] = $scope.ageBrackets[value.age] + 1 || 1; }); $scope.addPerson = function() { var age = Math.floor(Math.random() * (123 - 1 + 1)) + 1; // random between 1 and 123 $scope.people.push({ name: 'Person ' + ($scope.people.length + 1), age: age }); $scope.ageBrackets[age] = $scope.ageBrackets[age] + 1 || 1; }; $scope.ageBracketCount = function(min, max) { max = max || Number.MAX_SAFE_INTEGER; return $scope.ageBrackets.filter(function(value, index, array) { return index >= min && index <= max; }).reduce(function(a, b) { return a + b; }, 0); }; } ]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="ageBracketApp" ng-controller="ageBracketController"> {{people}} <hr />18+: {{ageBracketCount(18)}} <br />18-25: {{ageBracketCount(18,25)}} <br />26-35: {{ageBracketCount(26,35)}} <br />40-: {{ageBracketCount(0,40)}} <hr /> <button ng-click="addPerson()"> Add person </button> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM