2015-10-22 32 views
1

假設我有一個蘋果列表,並且我想在每個籃子中放置4個蘋果。在HTML中,它看起來就像這樣:Angularjs ng-repeat爲每個第四項開始一個新行?

<div class="basket"> 
    <span class="apple">Green</span> 
    <span class="apple">Green</span> 
    <span class="apple">Green</span> 
    <span class="apple">Green</span> 
</div> 

<div class="basket"> 
    <span class="apple">Green</span> 
    <span class="apple">Green</span> 
    <span class="apple">Green</span> 
    <span class="apple">Green</span> 
</div> 

我希望能夠做到這一點使用NG-重複在Angualrjs:

<div class="basket" ng-repeat="apple in apples> 
    <span class="apple">{{apple.color}}</span> 
</div> 

,每4個蘋果創建一個新籃等

+1

所以,我看到它的方式,這可以是一個模式問題或視覺問題。如果這是一個視覺問題,最好用css做一些事情,甚至可以像Pankaj所建議的那樣使用一個框架來緩解這個問題。如果它不是一個視覺問題,看起來你應該有一些包含蘋果集合的籃子物品。你需要重複籃子,然後在籃子內,重複該籃子的蘋果收藏。 –

回答

-1

如果你知道basket類的寬度,那麼你可以設置與apple類是總寬度的25%:

.basket { 
    width: 500px; 
} 
.apple { 
    width: 125px; 
} 
+0

不要只是當人們討厭但不發表評論時才討厭它?這就像他們害怕討論他們的推理。 –

0

我認爲你最好的答案在於你如何構建你的模型。我會以層次的方式填充它,以最好地支持html中所需的呈現。

控制器

app.controller('MainCtrl', function($scope) { 
    $scope.appleBaskets = [{ 
    basketId: 1, 
    apples: [{ 
     color: 'green' 
    }, { 
     color: 'red' 
    }, { 
     color: 'gold' 
    }, { 
     color: 'red' 
    }, ] 
    }, { 
    basketId: 2, 
    apples: [{ 
     color: 'green' 
    }, { 
     color: 'red' 
    }, { 
     color: 'green' 
    }, { 
     color: 'yellow' 
    }] 
    }, { 
    basketId: 3, 
    apples: [{ 
     color: 'green' 
    }, { 
     color: 'red' 
    }, { 
     color: 'green' 
    }, { 
     color: 'red' 
    }] 
    }] 
}); 

HTML

<body ng-controller="MainCtrl"> 
    <div ng-repeat="appleBasket in appleBaskets"> 
    <div>{{appleBasket.basketId}}</div> 
    <div ng-repeat="apple in appleBasket.apples"> 
     <span>{{apple.color}}</span> 
    </div> 
    </div> 
</body> 
0

一種方法是爲具有basket秒的陣列,每個包含的apple秒的陣列。然後,你可以窩ng-repeat S作爲如此...

<div class="basket" ng-repeat="basket in baskets"> 
    <span class="apple" ng-repeat="apple in basket.apples">{{apple.color}}</span> 
</div> 

如果你只是想擁有蘋果,而不是包含蘋果的籃子,那麼你可以讓視覺上蘋果組成四肢的2維數組的一個維數組與CSS。

做到這一點的一種方法是設置一個名爲new-line的CSS類,並將其定義爲設置display: block;或任何你想用來強制新行的東西。

然後使用ng-class根據$index值動態設置CSS。

<div class="basket" ng-repeat="apple in apples" ng-class="{ 'new-line' : $index % 4 === 0 }"> 
    <span class="apple">{{apple.color}}</span> 
</div> 
1

你有沒有試過,NG-如果

<div ng-repeat="apple in apples" ng-if='$index % 4 == 0' class='basket'> 
     <span class="apple"> {{apples[$index].color}}</span> 
     <span class="apple"> {{apples[$index +1 ].color}}</span> 
     <span class="apple"> {{apples[$index + 2].color}}</span> 
     <span class="apple"> {{apples[$index + 3].color}}</span> 
    </div> 

See the plunker

相關問題