olivier olivier - 4 months ago 32
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">
<h1>BAROCK</h1>
<h4>Bester Kaffee der Stadt</h4>
<img src="img/home/open.png" alt="">
</div>
</div>


And I would like to reorder all of them.

Answer

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 () {

            console.log('called');
            var divs = elem.find('div');
            console.log(divs);

            divs = shuffle(divs);
            var content = $compile(divs)(scope);
            elem.append(content);
        })
    }
})

and here is the template:

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

  <body ng-controller="MainController">
    <div reorder-div>
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
    </div>
  </body>
</html>

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.