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?

davidx1
  • 3,525
  • 9
  • 38
  • 65
  • 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. – Erick May 17 '16 at 00:02

1 Answers1

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

Community
  • 1
  • 1
Fizzix
  • 23,679
  • 38
  • 110
  • 176
  • 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. – davidx1 May 17 '16 at 05:14
  • @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. – Fizzix May 17 '16 at 05:23