简体   繁体   English

在angular.js控制器中过滤和计数数组

[英]Filter and count array in angular.js controller

I have an array of objects in my Angular app and each has a "ready" field, which is a timestamp. 我的Angular应用程序中有一个对象数组,每个对象都有一个“就绪”字段,这是一个时间戳。 I want to count the number of objects where the ready timestamp is earlier than the current time. 我想计算就绪时间戳早于当前时间的对象数。 How would I do this? 我该怎么做?

I have: 我有:

$scope.getDatetime = new Date();
$scope.numberReady = $filter('filter')($scope.array, {ready <  $scope.getDatetime}).length;

Obviously I can't use ready < $scope.getDatetime , but that, logically speaking, is what I want to do. 显然,我不能使用ready < $scope.getDatetime ,但是从逻辑上讲,这就是我想要的。

You can use pure ES5 filter method, no need of Angular here: 您可以使用纯ES5过滤器方法,这里不需要Angular:

$scope.getDatetime = new Date();
$scope.numberReady = $scope.array.filter(function(obj) {
    return obj.ready < $scope.getDatetime;
}).length;

... although you could use Angular filter here too: ...虽然您也可以在此处使用Angular过滤器:

$scope.getDatetime = new Date();
$scope.numberReady = $filter('filter')($scope.array, function(obj) {
    return obj.ready <  $scope.getDatetime;
}).length;

but since it's just a wrapper around native thing, this is not ideal in this case. 但是由于它只是原生对象的包装,因此在这种情况下并不理想。

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

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