ng-repeat order by string value

ng-repeat order by string value



I was wondering if it is possible to order by a list based on a string, for e.g.



I want all the Bear's to come first in my ng-repeat based on item.type.


Bear


item.type



Data:


$scope.Reindeers = [
"name": "Vixen",
"type": "Bear"
,

"name": "Prancer",
"type": "Dog"
,

"name": "Dancer",
"type": "Cat"
,

"name": "Rudolph",
"type": "Bear"
]



AngularJS e.g.


<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: 'type == Bear'"></div>






Try: ng-repeat="Deer in Reindeers | orderBy: 'type'". Réf: docs.angularjs.org/api/ng/filter/orderBy

– Jonathan Anctil
Sep 10 '18 at 14:55






But how does this priorite that Bears come first. In some instances of the data, Bears are not the most popular type.

– Connor Simpson
Sep 10 '18 at 15:00


Bears


Bears






It's not an alphabetic sort on type column?

– Jonathan Anctil
Sep 10 '18 at 15:09




3 Answers
3



The argument to orderBy can be a function: https://docs.angularjs.org/api/ng/filter/orderBy#orderBy-arguments


orderBy



Write a function that returns a value used for sorting. The highest priority should return the lowest value:


$scope.orderByBears = function(item)
switch(item.type)
case "Bear":
return -10;
/*case "Dog":
return -5;*/
default:
return 0;




Then use this as your orderBy function:


orderBy


<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: orderByBears"></div>



https://jsfiddle.net/jnokyfx9/2/



The easiest solution is to just use the default alphabetical ordering.



So since bear starts with a b, it's enough to just write:


<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: 'type'">Deer</div>



See: https://jsfiddle.net/nfje5qo2/6/



As your array is stored in key: value manner. This is easy to sort. You need not require to write any further method or function. Just put a pipeline called filter in Angular terms in your HTML as below.


<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: 'type'">Deer</div>



Thanks for contributing an answer to Stack Overflow!



But avoid …



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Malaysia to Papua New Guinea by motorcycle?

List of Bhojpuri films

.name