Dynamic order in AngularJS

I have an array of objects that I want to order dynamically, based on the value from the dropdown menu. This is what I still have on my list:

ng-repeat="item in filteredItems = (items | filter:searchInput | orderBy:canBeAnything)" 

However, the problem is that sorting can be an attribute of an object or a computed value using a function. It should also be able to sort in descending order (optional).

I know that I can use the string for the canByAnything variable for orderBy, passing the attribute of an object, for example:

 "-creationDate" // descending ordering on creation date "customer.lastname" // ascending ordering on customers last name 

I also know that I can order the function:

 orderBy:myCalculatedValueFunction // will order in an ascending way based on a calculated value, for example calculating the total price of the object if it was an order or something 

But I do not know and want to achieve:

  • How to combine it so that I can use functions for sorting in combination with attributes / properties of objects. I mean one or the other, dynamically, based on what the user selected. Which can be an attribute or a computed value, neither descending nor ascending.
  • How to sort the calculated value in descending order.
+6
source share
2 answers

Update orderBy:myCalculatedValueFunction approximately orderBy:dynamicOrderFunction :

 $scope.dynamicOrderFunction = function() { if (orderByString) { return '-creationDate'; } else { return myCalculatedValueFunction; } } 

orderBy also has a third property, which takes a boolean and overrides orderBy when true . ( orderBy:dynamicOrderFunction:reverseOrder where $scope.reverseOrder = true; // or false )


change

In fact, you will run into problems trying to switch orderBy between the line. Checkout this jsfiddle for dynamic ordering.

+10
source

So, you need to create your own filter and do what you want in it, there are tons of google example. Just do a search:

angular custom filter

Abstracts of the last days, I have problems with creating filters, and I found that: https://github.com/a8m/angular-filter

I added it immediately to my dependencies, I know that I will use it in the near future. Maybe this will help too. Do not forget to confirm your answer if it helps you solve your problem;)

0
source

Source: https://habr.com/ru/post/985138/


All Articles