1

This doesn't seem to work. Is it ok to pass arguments to the random() callback?

function getAnswers($scope){
    $scope.answers = conjugate("작다");
    $scope.$on('$viewContentLoaded', random($(".answer")));
} 

function random(r) {
    r.children().sort(function() {
        return (Math.round(Math.random()) - 0.5);
    }).appendTo(r);
};
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
Tules
  • 4,905
  • 2
  • 27
  • 29

1 Answers1

1

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.

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232
  • thank you Blesh, I'm coming from a purely jQuery background and have never used a proper MVC framework before so I think it's gonna take a while before I adjust to the new paradigm! – Tules Feb 21 '13 at 18:13
  • It's okay... some large percentage of Angular questions are like this. – Ben Lesh Feb 21 '13 at 18:14
  • conjugate is not asynchronous, I just thought I should wait until the DOM was ready to manipulate. I want the results to be randomized every time so should I also be calling the function from within the controller like this? $scope.randomizeAnswers = function () { fisherYates($scope.answers); }(); – Tules Feb 21 '13 at 18:20
  • 1
    You don't need to wait for anything to be ready. You just need up update your scope values, and wait for Angular to do it's thing (in a $digest). Putting the function on `$scope` just makes it available to be called from the view (in an ng-click for example), or wherever references the scope. You could also call it immediately if you wanted. – Ben Lesh Feb 21 '13 at 18:23