This isn't really the "Angular way" to do this.
You're not supposed to be doing any DOM manipulation or even referencing the DOM in your controller.
Instead, what you'd want to do is manipulate model data that affects your view. In your case, I'd randomize the array of data, rather than randomize the DOM elements themselves.:
function MyCtrl($scope) {
$scope.answers = [ /*... some data here ... */];
$scope.randomizeAnswers = function () {
fisherYates($scope.answers);
};
//a good randomization function
//(see: http://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array)
function fisherYates ( myArray ) {
var i = myArray.length, j, tempi, tempj;
if ( i == 0 ) return false;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
tempi = myArray[i];
tempj = myArray[j];
myArray[i] = tempj;
myArray[j] = tempi;
}
}
}
The use of $on is probably unnecessary here, it seems like you just want to randomize after the array is loaded? That's really going to depend on what in the world your conjugate()
method is doing.
I have no idea what your conjugate()
method does... but presuming it does some sort of Asynchronous work to return data, you might have to use $q
and return a promise from that method. Then you can put your randomization call in a .then()
callback that would fire when the data is loaded.