AngularJS试图了解JS过滤器过滤器、AngularJS、JS

2023-09-14 00:13:22 作者:愛似罂粟↘狠美卻有毒

试图了解的AngularJS大部分示例对视图/ HTML侧的过滤器,但我需要它在控制器/ JS侧的过滤器的功能。

Trying to understand the "filter" function of AngularJS most of the examples have the filters on the view/HTML side but I need it on the controller/JS side.

此工作

  $scope.getPickedPeopleCount = function(){
    var thisCount = 0;
    angular.forEach($scope.allPeople, function(person){
      if(person.PICKED){thisCount++}
    });
    return thisCount;
  }

但这种失败

  $scope.getPickedPeopleCount = function(){
    return $scope.allPeople.filter(PICKED:'true').length;
  }

显然,我的语法是错误的,可有人点我在正确的方向

Obviously my syntax is wrong, can someone point me in the right direction

推荐答案

要在控制器使用过滤器,就必须注入$过滤服务,然后通过名称请求过滤器:

To use a filter in a controller, you must inject the $filter service and then request the filter by name:

function MyCtrl ( $scope, $filter ) {
  var filter = $filter('filter'); // could be orderBy, etc.

  // more code...

  $scope.getPickedPeopleCount = function () {
    return filter( $scope.allPeople, { PICKED: 'true' } ).length;
  }
}
 
精彩推荐
图片推荐