如何在ng-show中多次显示相同的元素?

时间:2017-01-23 01:14:38

标签: javascript angularjs

我正在玩一个纸牌游戏应用程序,我想要一个卡片图像显示手形阵列中的每个实例。为了简单起见,我希望显示card1.png,如果数组看起来像[1,2,3,4,5]。但是,如果数组看起来像[1,1,3,4,5],我希望图像显示两次。到目前为止,我可以让它显示一次。

的index.html

<div ng-repeat="hand in hands track by $index">
    Player {{$index}} hand: {{ hand }}
    <img src="/images/faces-one.png" ng-show="numberInArray(hand, 1)">
    <img src="/images/two.png" ng-show="numberInArray(hand, 2)">
    <img src="/images/three.png" ng-show="numberInArray(hand, 3)">
    <img src="/images/four.png" ng-show="numberInArray(hand, 4)">
    <img src="/images/five.png" ng-show="numberInArray(hand, 5)">
    <img src="/images/six.png" ng-show="numberInArray(hand, 6)">  
</div>

App.js

$scope.numberInArray = function(hand, num) {
  var found;
  found = hand.includes(num) ? true : false;
  return found;
}

2 个答案:

答案 0 :(得分:0)

我并不是说这是最好的解决方案,而是要修复你目前所拥有的(或者至少看起来有的)......

在每张图片上使用另一张(嵌套)ng-repeat而不是ng-show。您应该能够将它附加到getNunbersInArray(n)函数,该函数返回主数组的子集,然后可以循环所需的次数。

例如,如果主阵列中有[1,1,3,4,5],则连接到新ng-repeat的函数将返回[1,1](传递1时)和[2](当通过2)等时。

您不需要对这些新数组中返回的值执行任何操作,唯一重要的是它们包含正确数量的元素以确保图像重复正确的次数。

答案 1 :(得分:0)

根据我收到的评论,这是我实施的解决方案:

<强>的index.html

<div ng-repeat="hand in hands track by $index">
     Player {{$index}} hand:
     <div ng-repeat="card in hand track by $index">
         <img ng-src="/images/{{card}}.png">
     </div>
</div>

删除了numberInArray函数,因为它不是必需的。基本上,这现在遍历数组数组,并显示在ng-src上找到的图像,在这种情况下是1.png,2.png等。这实现了我的目标,即显示每个数字的卡片图像数组,无论其数量如何。

相关问题