如何使此JS显示下一张卡片而不是随机卡片?

时间:2019-03-31 12:45:07

标签: javascript jquery html css angularjs

我正在使用HTML,CSS和JS进行刷卡项目。

我从Codepen中获取了此JS代码,并实现了它,但问题是卡在随机化。如何使其按顺序排列(不重复)?

angular.module('starter', ['ionic', 'ionic.contrib.ui.cards'])
  .directive('noScroll', function($document) {
    return {
      restrict: 'A',
      link: function($scope, $element, $attr) {
        $document.on('touchmove', function(e) {
          e.preventDefault();
        });
      }
    }
  })

  .controller('CardsCtrl', function($scope, $ionicSwipeCardDelegate) {
    var cardTypes = [
      {title: '1'},
      {title: '2'},
      {title: '3'},
      {title: '4'},
      {title: '5'}
    ];

    $scope.cards = Array.prototype.slice.call(cardTypes, 0, 0);

    $scope.cardSwiped = function(index) {
      $scope.addCard();
    };

    $scope.cardDestroyed = function(index) {
      $scope.cards.splice(index, 1);
    };

    $scope.addCard = function() {
      var newCard = cardTypes[
        Math.floor(Math.random() * cardTypes.length)
      ];
      newCard.id = Math.random();
      $scope.cards.push(angular.extend({}, newCard));
    }
  })

  .controller('CardCtrl', function($scope, $ionicSwipeCardDelegate) {
    $scope.goAway = function() {
      var card = $ionicSwipeCardDelegate.getSwipeableCard($scope);
      card.swipe();
    };
  });

2 个答案:

答案 0 :(得分:0)

我将更改以下内容:

$scope.cards = Array.prototype.slice.call(cardTypes, 0, 0);

替换为:

$scope.cards = cardTypes; // this keeps the series ordered as is defined

您可能需要.reverse()卡类型,因此阵列中的第一项是第一张卡(实际上是从阵列中弹出卡,因此如果您不反转,则最后一项将是第一张卡) ):

$scope.cards = cardTypes.reverse(); // reverse the array

然后看来,每次刷卡后都会随机添加新卡:

$scope.cardSwiped = function(index) {
  $scope.addCard();
};

也许您可以对整个内容进行评论,或者如果$scope.addCard()破坏了应用程序,则可以评论。

答案 1 :(得分:0)

问题出在您的$scope.addCard上 获取新卡时,您正在使用Math.Random

正确的方式-

    var cardCount = -1;//    
    $scope.addCard = function () {
        if (cardCount < cardTypes.length - 2) {
            cardCount++;//get the next card
        }
        else {
            alert("Reached last card");//last card reached
        }
        var newCard = cardTypes[cardCount];
        newCard.id = cardCount;
        $scope.cards.push(angular.extend({}, newCard));
    }