1

I pull in a JSON object with my controller below, but how do I make the order random, on each page refresh?

app.controller('MainCtrl', ['$scope', '$http', 'makeRandom', function ($scope, $http, makeRandom) {
$http.get('projects/projects.json').success(function(data) {
  $scope.works = data; 
   });
 makeRandom.forEach($scope.works, function(work) {
  work.rank = Math.random();
  });    
}]);

template.html

 <section ng-repeat="work in works | orderBy:'rank'" class="showcase {{work.class}}">
  ...
</section>
  • possible duplicate of http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – charlietfl Dec 08 '14 at 14:31
  • not sure, as the problem i have is getting data from a Http request and randomizing that data for each scope inside a ng-repeat. – cheers_to_you Dec 12 '14 at 12:33

1 Answers1

1

You pretty much have all the work done, you just need to put it together:

This is based off your work:

app.controller('myCtrl', ['$scope', '$http', function($scope, $http){

  $http.get('projects/projects.json').success(function(data) {
    $scope.works = data; 
  }).error(function(){

    // works on error response because I don't have your code, just copy this to success response
    // here I just generate a list of ids and then randomize them
    var works = [];
    for(var i=0; i< 20; i++){
      works.push({id: i});
    }
    $scope.works = makeRandom(works);
  });

  function makeRandom(inputArray){
    angular.forEach(inputArray, function(value){
      value.rank = Math.random();
    });
    return inputArray; 
  }

}]); 

HTML:

<section ng-repeat="work in works | orderBy:'rank'" class="showcase {{work.class}}">
    {{work.rank}} {{work}} 
</section>

Here is a working example: http://plnkr.co/edit/xIwD0zWdodnYSIupm1va?p=preview

SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98
  • Thanks SoluableNonagon. I'd like to loop on the works.length, but then doesn't work. `app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) { $http.get('projects/projects.json').success(function(data) { $scope.works = data; }).success(function(){ var works = []; for(var i=0; i< this.length; i++){ works.push({id: i}); } $scope.works = makeRandom(works); }); function makeRandom(inputArray){ angular.forEach(inputArray, function(value){ value.rank = Math.random(); }); return inputArray; } }]);` – cheers_to_you Dec 08 '14 at 22:40
  • hey @cheers_to_you , can you put together a plunker (just fork the link above) and replicate the issue you're having? – SoluableNonagon Dec 09 '14 at 15:39
  • g'day @SoluableNonagon, here's my plunker (http://plnkr.co/edit/pk7Jp4Obk4YJwvhTgRop?p=preview) you can see i added `this.length` but the list never refreshes as a random list, its always in the same order. Really appreciate your expert help. Thanks. – cheers_to_you Dec 09 '14 at 23:19
  • any ideas on finding the length of my array and returning that for the works.data? @SoluableNonagon – cheers_to_you Dec 11 '14 at 23:09