olivier olivier - 1 year ago 108
AngularJS Question

Shuffle divs with angularJS

I'm building an app with ionic and i search a way to shuffle divs each time the user loads the screen. I don't use ng-repeat, is there an other way to reorder some divs on a refresh?

Any help much appreciated!

One div looks like this:

<div class="barock center">
<div class="inner">
<h4>Bester Kaffee der Stadt</h4>
<img src="img/home/open.png" alt="">

And I would like to reorder all of them.

Answer Source

I just come up with this solution, and haven't really worked on it, just to give you idea!

Here we have a directive:

var app = angular.module('app', [])
.controller("MainController", function(){});

app.directive('reorderDiv', function ($compile) {
    return function (scope, elem, attrs) {

        function shuffle(array) {
            var currentIndex = array.length, temporaryValue, randomIndex;

            // While there remain elements to shuffle...
            while (0 !== currentIndex) {

                // Pick a remaining element...
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex -= 1;

                // And swap it with the current element.
                temporaryValue = array[currentIndex];
                array[currentIndex] = array[randomIndex];
                array[randomIndex] = temporaryValue;

            return array;
        elem.on('click', function () {

            var divs = elem.find('div');

            divs = shuffle(divs);
            var content = $compile(divs)(scope);

and here is the template:

<html ng-app="app">
    <script src="bower_components/angular/angular.js"></script>
    <script src="app.js"></script>

  <body ng-controller="MainController">
    <div reorder-div>

what does this directive do? It just gathers all divs inside the element which I have applied my directive and shuffle those divs, shuffle them and change the , use $compile service to compile it against the scope, and set the content of outer div to the shuffled compiled temple.

If you click on outer dive, you will see that its content are shuffled.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download