2017-05-13 32 views
2

我在ng-repeat中的元素中使用了ng類函數。我得到這個錯誤。我試圖從數組中選擇一個隨機類。我該如何解決這個問題?

<div class="col-lg-4" ng-repeat="client in allClients"> 
<div class="someClass" ng-class="getClass()"> 
//some data 
{{client.name}} 
</div> 
</div> 

這是我的JS代碼。

$scope.getClass = function() { 
var classArray = ['infobox1', 'infobox2', 'infobox3', 'infobox4', 'infobox5', 'infobox6']; 
return classArray[Math.floor(Math.random() * classArray.length)]; 
} 

錯誤在繼續。 Watchers在最近5次迭代中觸發:[[{「msg」:「getBackgroundClass()」,「newVal」:「infobox4」,「oldVal」:「infobox6」},{「msg」:「getBackgroundClass() 「的newval」: 「infobox4」, 「OLDVAL」: 「infobox5」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox1」, 「OLDVAL」: 「infobox4」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox5」, 「OLDVAL」: 「infobox1」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox1」, 「OLDVAL」: 「infobox4」} ,{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox6」, 「OLDVAL」: 「infobox4」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox1」,「OLDVAL 「:」 infobox5 「},{」 msg 「中:」 getBackgroundClass()」, 「的newval」: 「infobox1」, 「OLDVAL」: 「infobox2」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox1」, 「OLDVAL」: 「infobox4」}],[{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox6」, 「OLDVAL」: 「infobox4」},{ 「msg」 中:「getBackgroundClass ()」, 「的newval」: 「infobox1」, 「OLDVAL」: 「infobox4」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox4」, 「OLDVAL」: 「infobox1」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox5」, 「OLDVAL」: 「infobox1」}, { 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox4」, 「OLDVAL」: 「infobox5」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox2」, 「OLDVAL」 : 「infobox6」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」: 「infobox6」, 「OLDVAL」: 「infobox1」},{ 「msg」 中: 「getBackgroundClass()」, 「的newval」:」 infobox6「,」oldVal「:」infobox1「},{」msg「:」getBackgroundClass()「,」newVal「:」infobox4「,」oldVal「:」infobox1「

回答

1

您多長時間想要選擇隨機課?目前,您已經創建了一個無限循環,因爲angular會一直注意到類已更改,運行摘要循環以注意其他更改,發現類再次發生變化,運行摘要循環以注意其他更改,發現類已更改再次,等等...

你的方式要挑隨機值一次,並堅持了一會兒:經常你想

$scope.randomClass = classArray[Math.floor(Math.random() * classArray.length)] 

(隨意執行上面的代碼看到一個新的值)

+0

謝謝。就一次。對於在ng-repeat中創建的所有孩子,他們應該從該數組中分配隨機類。 所以我應該只更換函數中的代碼行並返回$ scope.randomClass? – Aijaz

+0

你的意思是這樣的http://plnkr.co/edit/zneFGuonAVuZYG0fey7J?p=preview –

+0

啊,我沒有注意到ng-repeat。既然你可能希望每一次迭代都使用一個獨立選擇的類,你需要每個迭代都有一個scope變量,比如Zama的答案和plunkr。 – meriton

0

這裏是工作例子 http://plnkr.co/edit/pl3W5uNofz123EJZnMT8

我做了一個班陣列時,我有我的allClients所有值的數組,然後使用該數組分配類

$scope.allClients = [{name: 'client'}, {name: 'client2'}, {name: 'client3'}]; 
    var classes = $scope.allClients.map(function(client) { 
    var classArray = ['infobox1', 'infobox2', 'infobox3', 'infobox4', 'infobox5', 'infobox6']; 
    return classArray[Math.floor(Math.random() * classArray.length)]; 
    }); 
相關問題