Why are the advantages or filter and orderBy?

余生长醉 提交于 2019-12-21 04:27:47

问题


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!


回答1:


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!



来源:https://stackoverflow.com/questions/11761858/why-are-the-advantages-or-filter-and-orderby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!