基于ID动态列表的角度过滤器

时间:2015-10-02 10:27:37

标签: javascript angularjs angular-filters

在我的Angular应用中,我希望根据我已动态生成的ID列表,使用ng-repeat过滤下拉按钮上生成的项目。

此列表基本上是一个数字数组,可以使用$scope.$watchCollection动态更新,例如:

$scope.selectedBPs = [1, 2]

我在前面提到的dropdwon按钮上使用ng-repeat生成的每个项目都有一个id属性。我希望过滤器执行的操作是仅在$scope.selectedBPs包含其ID时显示特定项目。

目前我的HTML是:

<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li ng-repeat="marker in vm.markers" ng-click="progressMarkerSelected.name = marker.name;">
        <a href role="menuitem" tabindex="-1">{{marker.name}}</a>
    </li>
</ul>

所以基本上,我只希望标记出现在$scope.selectedBPs.indexOf(marker.bpId) > -1(bpId是项目的ID)。

是否可以使用过滤器执行此操作?

如何将$scope.selectedBPs传递给角度过滤器,以便每当列表更改时下拉列表也会动态更新?

1 个答案:

答案 0 :(得分:2)

您可以在Angular中创建自己的自定义过滤器,它可以执行您想要的任何操作,语法很简单,例如:ng-repeat =&#34; vm.markers中的标记| filter:myAmazingFilter&#34;。

在此自定义过滤器中,您将收到可迭代项作为参数,因此您可以进行测试以显示与否。

请参阅以下示例:

&#13;
&#13;
var app = angular.module("app", []);

app.controller('ListCtrl', function($scope){
 
  $scope.cars = [
    {
      id: 1,
      'name': 'Mustang'
    },
    {
      id: 2,
      'name': 'Corvette'
    },
    {
      id: 3,
      'name': 'Camaro'
    },
    {
      id: 4,
      'name': 'Ford GT'
    }
  ];
  
  $scope.selectedIDs = [1,3];
  
  $scope.myCustomFilter = function(item){
    
    if ($scope.selectedIDs.indexOf(item.id) >= 0){ //Return true if item.id is Mustang or Camaro
      
      return true; //Return true to show your item in repeat
      
    }
    
    return false;
    
  }
 
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="ListCtrl">
  
    <ul ng-repeat="car in cars | filter: myCustomFilter">
      <li>{{car.name}}</li>
    </ul>
    
  </div>
</div>
  
&#13;
&#13;
&#13;