Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the advantages or filter and orderBy?

It seems that AngularJS really puts an heavy emphasis on using filters and other ng directive in your view to filter and sort your data, instead of doing it manually in the model. Is there any reason for that, ie is it faster, cached, or something?

I want to show a list sorted for example, but I also want to access the sorted list for other purposes that are not view related. It's very easy if the list is directly sorted in the model, so I'm trying to understand if there is a drawback to doing it this way.

Thanks!

like image 908
ciryus Avatar asked Aug 01 '12 14:08

ciryus


1 Answers

I don't see anything wrong with pre-sorting the data if it makes sense to you but here are some pros and cons for using Angular filters.

Pros:

  • Clear separation of the view and model. The model/controller does not need to be aware of or include code related to how the data will be displayed/sorted/filtered
  • Since filters are executed as the model changes the orderBy filter can automatically sort as items are added to an array via the UI
  • Filters can be used to format data for display (the currency filter for instance) as well as modify the DOM adding/removing items (the filter filter for instance) without modifying the underlying model data
  • Promotes reuse of commonly used built in or custom filter functions

Cons:

  • Poorly written filter function can cause performance issues. You can see a purposely contrived example in the AngularJS Batarang video starting at 4:30. Any code (not just a filter) can be written poorly but it's not initially obvious how often a filter gets called.
  • Slightly confusing in that some filters act on a single number/string (currency filter) and some on arrays (orderBy filter)
  • Syntax to pass arguments and chaining of filters can also be a bit confusing

I'm sure there are many more pros/cons but hopefully this helps!

like image 86
Gloopy Avatar answered Oct 20 '22 04:10

Gloopy