Filter by multiple columns with ng-repeat

前端 未结 8 1475
小鲜肉
小鲜肉 2020-11-30 12:16

I\'m wondering if there\'s an easy way in Angular to filter a table using ng-repeat on specific columns using or logic, rather than and

相关标签:
8条回答
  • 2020-11-30 13:05

    I figured it out- I had to write my own custom filter. Here is my solution:

    var filteredData;
    
    filteredData = $filter('filter')(data, function(data) {
      if ($scope.filter) {
        return data.id.toString().indexOf($scope.filter) > -1 || data.name.toString().indexOf($scope.filter) > -1;
      } else {
        return true;
      }
    });
    
    0 讨论(0)
  • 2020-11-30 13:06

    Easily We can do this type Following written code according you will easily create another field filter....

    var myApp = angular.module('myApp',[]);
    
    myApp.filter('myfilter',myfilter);
    
    function myfilter(){
       return function (items, filters) {
            
            if (filters == null) {
                return items;
            }
    
            var filtered = [];
            //Apply filter
            angular.forEach(items, function (item) { 
                if ((filters.Name == '' || angular.lowercase(item.Name).indexOf(angular.lowercase(filters.Name)) >= 0) 
                   )
                {
                    filtered.push(item);
                }
    
            });
            return filtered;
        };
    }
    
    myApp.controller('mycontroller',['$scope',function($scope){
      $scope.filters={Name:'',MathsMarks:''};
      $scope.students=[];
      var i=0;
      for(i=0;i<5;i++){
        var item={Name:'',Marks:[]};
      
        item.Name='student' + i;  
        item.Marks.push({Maths:50-i,Science:50 +i});
        
        $scope.students.push(item);
      }
    
    }]);
    <html ng-app='myApp'>
      <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
    </head>
      <body ng-controller='mycontroller'>
        <input type='text' name='studentName' ng-model="filters.Name" placeholder='Enter Student Name'>
        <div ng-repeat="student in students | myfilter: filters">
          Name : {{student.Name}} Marks == >
          <span ng-repeat="m in student.Marks">Maths:{{m.Maths}} Science:{{m.Science}}</span>
          </div>
      </body>
    </html>

    0 讨论(0)
提交回复
热议问题