2

I know that in angular, to apply a custom filter with ng-repeat will look something like this:

ng-repeat="request in allRequests | allRequests"

But I've got a couple of different filters. eg.

 allFutureRequests, allPastRequests, myPastRequests, group1FutureRequests

and I was hoping to swap out the 'allRequests' filter and replace it with any of the other filters dynamically, depending on what what some buttons the user clicks on.

How would I go about doing that?

1
  • 1
    An initial (Naive) implementation would be to declare the ng-repeat several times with an ng-if that displays the appropriate one depending on the selected radio button. A better one would be making a function that encompasses all of your filters and using the ng-model value for the filters button in an if else block, then using the appropriate filter depending on the value. I am not sure if what you want is possible, but if not the latter option would be worth a shot. Commented May 17, 2016 at 0:02

1 Answer 1

1

The simpliest way would be to just do this within the controller. This question sums it up quite nicely.

It works in the format of $filter('filtername')(argument)

If you want to add a filter to something on button click, do something like this:

$scope.onBtnClick = function(index) {
    $scope.allRequests[index] = $filter('allFutureRequests')($scope.allRequests[index]);
}

And you can call that from a click such as this:

<button ng-repeat="request in allRequests | allRequests" ng-click="onBtnClick($index)">

The above simply just passes the index of that allRequests array/object to the function. The function will then apply that filter to that specific index within it.

Also, don't forget to inject $filter into your controller.

WORKING EXAMPLE

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, the working Example doesn't really work. wrong link perhaps? Otherwise, I think I understand what to do. Thanks a lot! One note though for anyone else reading. $index may not work as expected if the order of the items are sorted in any other way.
@Synia - Yes wrong link sorry. Have updated it to the working link. Check it out. Let me know if you have any questions. track by is probably optional, although usually recommended. Try using a unique identifier instead such as an ID or GUID. I use track by often to speed up the performance of my app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.