【问题标题】:how to move filter outside of controller in angular如何以角度将过滤器移出控制器
【发布时间】:2014-05-05 10:19:13
【问题描述】:

我是 angular 新手。我设法使用 angular 进行过滤,它工作正常,但现在我想将过滤器移到控制器之外,这对我来说非常具有挑战性。

这是我的 html 页面:

<div >

    <input type="checkbox" ng-click="itemType('CAR')"/> CAR


    <input type="checkbox" ng-click="itemType('BIKE')"/> BIKE


    <input type="checkbox" ng-click="itemType('CYCLE')"/> CYCLE

</div>  
<table>
   <tbody>
          <tr ng-repeat="item in items | filter:filterItem">
            <td >{{item.name}}</td>
            <td >{{item.type}}</td>
          </tr>
    </tbody>
</table>

和控制器:

app.controller('MainCtrl', function($scope) {

 $scope.items = [
    {name: 'bmw', type:'CAR' },
    {name: 'ducati',type:'BIKE'},
    {name: 'airbas',type:'CYCLE' }
   ];

$scope.typeArray = [];
$scope.itemType = function(type) {
var i = $.inArray(type, $scope.typeArray);
if (i > -1) {
  $scope.typeArray.splice(i, 1);
} else {
  $scope.typeArray.push(type);
}
}

$scope.filterItem = function(item) {
if ($scope.typeArray.length > 0) {
  if ($.inArray(item.type, $scope.typeArray) < 0){
    return false;
  }
}
return item;
}
});

如何将过滤从控制器移动到 app.filter()。 谢谢。

【问题讨论】:

    标签: angularjs checkbox filter controller


    【解决方案1】:

    是的,自定义过滤器是一个单独的模块,你可以写成:

    iApp.filter('myfilter', function() {
       return function( items, types) {
        var filtered = [];
    
        var looping = function(name){
          angular.forEach(items, function(item) {
             if(item.type === name){
                 filtered.push(item);
               }
            });
        }
    
          if(types.car == true){
            looping('CAR');
          }
          if(types.bike == true){
            looping('BIKE');
          }
          if(types.cycle == true){
            looping('CYCLE');
          }
    
    
        return filtered;
      };
    });
    

    控制器:

    $scope.types = {car: false, bike:false, cycle: false};
    
       $scope.items = [
        {name: 'bmw', type:'CAR' },
        {name: 'ducati',type:'BIKE'},
        {name: 'airbas',type:'CYCLE' }
       ];
    

    演示1 Plunker

    [编辑]

    如果您想在未选中复选框时显示所有单元格,请将其添加到过滤器:

      var flag = true;
      angular.forEach(types, function(type){
        flag = flag & !type; // if one of flags will be false, we get flag=false
      });
    
      if(flag == true){
        return items;
      }
    

    演示2 Plunker

    仅供参考:您可以看到过滤器不使用$scope。如果你想传递额外的参数,语法应该是:

     <tr ng-repeat="item in items | filter:myfilter:types">
    

    types 是某个对象

    【讨论】:

    • 如何将选中的复选框函数参数传递给过滤器?它应该根据选中的复选框进行过滤。
    • 你用 ng-model 属性传递它们。
    • 但我使用的是 itemType() 函数而不是 ng-model。你能解释一下吗?
    • 然后将数组作为参数传递,filterItem:typeArray
    • 你的代码是多余的。只需连接复选框以使用 ng-model 进行过滤,您就不必在后端执行所有数组操作。
    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2016-03-21
    • 2016-01-10
    • 1970-01-01
    相关资源
    最近更新 更多