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

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

How do I collapse sections of code in Visual Studio Code for Windows?