点击angularjs上的重新加载和随机化内容

时间:2015-07-10 18:50:27

标签: angularjs

我构建了以下简单应用程序,它使用angularjs从instagram API加载到某些媒体中。我想要做的是在底部添加一个按钮,当您单击重新加载并随机化内容时。比如说,图片的长度现在是20,只显示了6,我只是想在每次点击按钮时显示20个随机中的6个。我该怎么做呢?

machinas.com/wip/machinas/instagramfeed /

HTML

(function(){
    //Place your own Instagram client_id below. Go to https://instagram.com/developer/clients/manage/ and register your app to get a client ID
  var client_id = '83aaab0bddea42adb694b689ad169fb1';
    //To get your user ID go to http://jelled.com/instagram/lookup-user-id and enter your Instagram user name to get your user ID
  var user_id = '179735937';

  var app = angular.module('instafeed', ['ngAnimate']);
    app.filter('getFirstCommentFrom',function(){
  return function(arr, user){
    for(var i=0;i<arr.length;i++)
    {
      if(arr[i].from.username==user)
        return arr[i].text;
    }
    return '';
  }
})

  app.factory("InstagramAPI", ['$http', function($http) {
    return {
      fetchPhotos: function(callback){
        var endpoint = "https://api.instagram.com/v1/users/self/media/liked/";
        endpoint += "?access_token=179735937.83aaab0.e44fe9abccb5415290bfc0765edd45ad";
        endpoint += "&callback=JSON_CALLBACK";
        /*   var endpoint = "https://api.instagram.com/v1/users/" + user_id + "/media/recent/?";
        endpoint += "?count=99";
        endpoint += "&client_id=" + client_id;
        endpoint += "&callback=JSON_CALLBACK";
*/
        $http.jsonp(endpoint).success(function(response){
          callback(response.data);

        });
      }
    }
  }]);

  app.controller('ShowImages', function($scope, InstagramAPI){
    $scope.layout = 'grid';
    $scope.data = {};
    $scope.pics = [];



    InstagramAPI.fetchPhotos(function(data){
      $scope.pics = data;
      console.log("length is "+data.length)
    });
  });


})();

JS

ajaxLoad(page, search);

1 个答案:

答案 0 :(得分:0)

<强> HTML

<button ng-click="shuffle()">
  Shuffle
</button>

JS (在ShowImages控制器内)

$scope.shuffle = function() {
  $scope.pics.sort(function() { return 0.5 - Math.random() });
}

$scope.shuffle = function() {
  for(var j, x, i = $scope.pics.length; i; j = parseInt(Math.random() * i), x = $scope.pics[--i], $scope.pics[i] = $scope.pics[j], $scope.pics[j] = x);
}

参考文献:

  1. How can I shuffle an array?
  2. https://css-tricks.com/snippets/javascript/shuffle-array/