Tuesday, 15 June 2010

AngularJS shuffle and limitTo a list -



AngularJS shuffle and limitTo a list -

i want utilize angularjs display shuffled list - first couple of elements. @ moment, perform both shuffling , limiting in html template, demonstrated in this fiddle:

class="lang-html prettyprint-override"><li ng-repeat="value in array | shuffle | limitto:1"> {{value}} </li>

this works fine, causes angular exceed 10 $digest iterations when there more items in list shown, in example. happening, far can tell, watching filtered , limited value of list, highly alter when there elements not displayed.

how should accomplish effect without breaking angular? of course, still works should, it's inefficient , indication i'm doing wrong , should achieved other way.

the obvious solution shuffle list in controller before ever displayed - want selection of elements displayed alter each time user updates view.

edit: here's better example of i'm trying accomplish - app lets switch between 2 lists, shuffled , limited each time.

as mentoined before - angular waits look gets stabilized. so, best way, shuffle array before passing view. anyway, there tricks, help maintain clean.

http://jsfiddle.net/zc3yh/3/

in fiddle cache shuffle result, while length keeps same. so, array reshuffled not when array changes, when length changed. can implement more complex caching behavior. so, main thought shuffle same array once, , reshuffle on array update.

current filter implementation bad, cause caches single array, if utilize filter twice - broken. so, caching should done using hashkey array differ different arrays.

shufflemodule.filter('shuffle', function() { var shuffledarr = [], shuffledlength = 0; homecoming function(arr) { var o = arr.slice(0, arr.length); if (shuffledlength == arr.length) homecoming shuffledarr; for(var j, x, = o.length; i; j = parseint(math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); shuffledarr = o; shuffledlength = o.length; homecoming o; }; });

anyway, not practice modify info in scope within filter. if need shuffled array shared - shuffle in controller/service/.... so, var o = arr.slice(0, length) copies array, maintain originar array unmodified.

angularjs

No comments:

Post a Comment