Itsik Mauyhas Itsik Mauyhas - 3 months ago 28
AngularJS Question

Angular filter table by text inside controller

I want to create a

filter
inside my
controller
that will operate like:

<tr ng-repeat = "obj in filterd = (allObjs | filter:{field: fieldFilter} | filter {field2: filed2Filter})"> //more filters...


so it will filter
allObjs
array by
fieldFilter
,
field2Filter
, inside my controler, I didn't understant how to do it using filter documnation:

$scope.filterTable = $filter('filter')(fieldFilter)(field2ilter); //doesn't work


Thanks.

Answer

$filter can take an object.

For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1".

Example using $filter in a controller:

angular.module('filters', [])
.controller('demo', function($scope, $filter) {
  $scope.example1 = [{
    name: 'C#',
    type: 'static'
  }, {
    name: 'PHP',
    type: 'dynamic'
  }, {
    name: 'Go',
    type: 'static'
  }, {
    name: 'JavaScript',
    type: 'dynamic'
  }, {
    name: 'Rust',
    type: 'static'
  }];

  $scope.filteredLanguages = $filter('filter')($scope.example1, {
    name: 'C#',
    type: 'static'
  });
})
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-lg-6 col-lg-offset-3">
        <div ng-app="filters">
          <div ng-controller="demo">
            <div class="panel panel-default">
              <div class="panel-body">
                <h4 class="text-center">AngularJS Filter</h4>
                <p><strong>Original:</strong>
                </p>
                <ul class="list">
                  <li ng-repeat="lang in example1">{{lang.name}}</li>
                </ul>
                <p><strong>Languages Filtered:</strong>
                </p>
                <ul class="list">
                  <li ng-repeat="lang in filteredLanguages">{{lang.name}}</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

</html>

Also, filter just returns an array so instead of the above you can call filter twice with each property key, see this answer.

var filtered;
filtered = $filter('filter')($scope.list, {name: $scope.filterParams.nameSearch});
filtered = $filter('orderBy')(filtered, $scope.filterParams.order);