Reusing An Angular.js Filter - View / Controller
This Solution is covering reusing Angular Filters. Which is yet another way to filter data, and Google landed me here when I needed such; and I like to share.
Use Case
If you are already filtering, say in an ng-repeat in your view (as below), then you might have defined a filter in the controller as further follows. And then you can reuse as in the final examples.
Filter Use Example - Filtered Repeat in View
<div ng-app="someApp" ng-controller="someController">
<h2>Duplicates</h2>
<table class="table table-striped table-light table-bordered-light">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in data | filter: searchDuplicate:true">
<td>{{person.name}}</td>
<td>{{person.gender}}</td>
</tr>
</tbody>
</table>
</div>
Angular Filter Definition Example
angular.module('someApp',[])
.controller('someController', function($scope, $filter ) {
$scope.people = [{name: 'Bob', gender: 'male' , hasDuplicate: true },
{name: 'Bob', gender: 'male' , hasDuplicate: true },
{name: 'Bob', gender: 'female', hasDuplicate: false}];
$scope.searchDuplicate = { hasDuplicate : true };
})
So, the concept here is that you are already using a filter created for your view, and then realize you would like to use it in your controller also.
Filter Function Use Within Controller Example 1
var dup = $filter('filter')($scope.people, $scope.searchDuplicate, true)
Filter Function Use Within Controller Example 2
Show a Button only if no duplicates are found, using the prior filter.
Html Button
<div ng-if="showButton()"><button class="btn btn-primary" ng-click="doSomething();"></button></div>
Show/Hide Button
$scope.doSomething = function(){ /* ... */ };
$scope.showButton = function(){ return $filter('filter')($scope.people, $scope.searchDuplicate, true).length == 0; };
Some may find this version of filtering easy, and it is an Angular.js option.
The optional comparator parameter "true" used in the view and in the $filter function call specifies you want a strict comparison. If you omit, values can be searched for over multiple columns.
https://docs.angularjs.org/api/ng/filter/filter