Shuffling array before/while running ng:repeat?

1,198 views
Skip to first unread message

Garreth.P

unread,
Mar 22, 2012, 1:11:39 AM3/22/12
to AngularJS
Hi there,

I'd like to know if there is a way to shuffle an array before
displaying DOMElements using ng:repeat.

I'm building a quiz application, and my situation is currently:
1. I've an array of Questions, each having an array of Answers.
2. I wish to shuffle the Answers to each question before displaying
it.
3. My App is currently displaying the problems using ng:repeat for
Questions, and a nested ng:repeat for Answers.

Once again, is there a good way i can use Angular to shuffle the array
of Answers before displaying it? Perhaps using JQuery?

Thanks!

Adam Bender

unread,
Mar 22, 2012, 11:21:41 AM3/22/12
to ang...@googlegroups.com
I believe what you want is to make use of a custom filter. Here is a fiddle that shows exactly that: http://jsfiddle.net/adambender/b8sxa/

Note that I borrowed the shuffle algorithm from here: http://snippets.dzone.com/posts/show/849

Hope that helps

Igor Minar

unread,
Mar 22, 2012, 2:55:20 PM3/22/12
to ang...@googlegroups.com
That works too, but it will cause the array to reshuffle every time angular tries to update the view.

I suggest that you just do one time shuffle of the array in your controller.

/i


--
You received this message because you are subscribed to the Google Groups "AngularJS" group.
To view this discussion on the web visit https://groups.google.com/d/msg/angular/-/UUoeq0EuxQAJ.

To post to this group, send email to ang...@googlegroups.com.
To unsubscribe from this group, send email to angular+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/angular?hl=en.

Johnny Hauser

unread,
Aug 15, 2014, 1:14:32 AM8/15/14
to ang...@googlegroups.com
The shuffle filter in that fiddle is causing an infinite digest - the common problem with filtering data that returns different data each time. I created a service that accepts a filter with that issue and returns a filter that uses caching to avoid the digest loop. It's simple to use and I've found it to be very helpful.

Here's the service: https://github.com/m59peacemaker/Angular.FilterStabilize

Here's my shuffle filter that uses that service: https://github.com/m59peacemaker/Angular.Shuffle

Johnny Hauser

unread,
Aug 22, 2014, 12:21:44 AM8/22/14
to ang...@googlegroups.com
I moved these to a single repo of my Angular components: https://github.com/m59peacemaker/angular-pmkr-components
Reply all
Reply to author
Forward
0 new messages