2

tl;dr What's the optimal way to filter large lists in Angular?


This is mainly about performance.

I have an array of objects that I list with ng-repeat. There will be hundreds to thousands of items. I now need to filter the list based on either:

  • A. a single, simple property (e.g. number)
  • B. multiple conditions (some expression)

What option is best:

  1. use a custom filter
  2. use ng-show / ng-hide
  3. use ng-if
  4. don't filter in the view at all -- maybe use service + controller (?)
  5. use ReactJS (?)

Details about the usecase:

  • I want to bind most of the objects' properties with :: one time binding, though some properties need two-way binding (score for sorting)
  • The list will be sorted dynamically, on fields independent from the fields used for filtering. Items filtered out probably should not be included in the sorting
  • The filtering needs to be dynamic

So I found Ben Nadel's post http://www.bennadel.com/blog/2487-filter-vs-nghide-with-ngrepeat-in-angularjs.htm but my question is meant to address general, standard usecases.

||||||
2

If you are on Angular 1.3, Angular filters have been optimized for performance. They are now stateless and do not execute (or re-evaluate) till the original data source changes. This was not the case with older version of Angular filters. Learn about these stateless filters here http://blog.thoughtram.io/angularjs/2014/11/19/exploring-angular-1.3-stateful-filters.html

For older version it would be better if you can do filtering in the controller or service, and always bind the filtered results to the view. This is about keeping an array such as $scope.filteredItem=[];, and updating it whenever the filter condition changes. You can still use angular filters in code, using the $filter service.

||||||
  • I actually need the filters to be stateful, as the filters will rely on a Service. I thought I would add some range slider and connect the value through a controller variable to a service property. So with stateless filters, that won't work. Perhaps there's another way? – wiherek Dec 29 '14 at 20:35
  • 1
    Stateful filter that rely on backend service can be a big performance killer. For stateful filters they are re evaluated on each digest cycle. Better would be to filter data before assigning to the view. – Chandermani Dec 30 '14 at 3:02
  • It is not a backend service that it relies upon, but a client-side service. – wiherek Dec 30 '14 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.