Aron Aron - 6 months ago 23
AngularJS Question

How do I conditionally add a filter to ng-repeat inside directive?

I am using an element directive on several views. The directive repeats for each 'resource' in a list of resources, simply like this:

ng-repeat="resource in resources"
.

Different page controllers will determine which resources will get pulled from the API by having a different
$scope.resourceApiPath
in each view controller that the directive controller then uses to make an
$http
call.

This works well for different views that display different resources. For example one view displays all the user's own resources, one view displays public resources, one view displays resources the user has starred, etc.

The only problem is that for one of my views I want to add a filter on the
ng-repeat
like so:
ng-repeat="resource in resources | filter:resourceSearch.text"
. is there a way for me to add this filter depending on a condition, e.g. if
$scope.filter == true;
, otherwise simply returning the regular
ng-repeat="resource in resources"
?

This is my directive:

.directive('resourcePanel', function() {
return {
restrict: 'E',
scope: false,
templateUrl: 'scripts/templates/resource-panel.html',
controller: 'ResourcesPanelController'
}
})


The
ResourcesPanelController
referenced in the directive has something like this:

$scope.resources = [];
$scope.loadResources = function() {
$scope.resources = []; // Empty the array
$http.get('/api/resource' + $scope.resourceApiPath)
.then(function(res) {
$scope.resources = res.data.message;
});
};
$scope.loadResources();


The
scripts/templates/resource-panel.html
element template looks something like this:

<div class="panel" ng-repeat="resource in resources">
{{resource.content}}
</div>


Thanks!

Answer

i think you can do one of four ways , i prefer 1 and 3 but its totally depend on your requirement and code standard which one suits best for you.

Custom filter is also a clean solution.

  1. If you are using text value for filter then, if you don't set the value of resourceSearch.text then its as good as no filter, so if resourceSearch.text exist it will filter and if its undefined then no filter.

    ng-repeat="resource in resources | filter:resourceSearch.text"

  2. Create a custom filter and handle it there.

if you want to create a custom filter then use enable argument which you can use to on and off your filter http://plnkr.co/edit/ilPJPUZkBC7Y5OvGHWey?p=preview i have found a plunkr as well for custom filter which suits your need

ng-repeat="resource in resources | customfilter:resourceSearch.text:enable"
  1. Filter your final resources in controller and pass filtered value to html

  2. use ng-if with your condition if filter exist then one loop and if its not there then different loop.

i hope it will help.