2015-12-17 17 views
2

我使用ng-repeat重複了一些項目,但是當$index碰到某個數字時,我想在該數字後改變$scope

所以我們可以說:我有一個ng-repeat,我有這個屬性:

ng-attr-cy="{{ team1.cy }}" 

,這在我的控制器$scope.team1.cy = 30;

$index > 8它改變了範圍的值設置爲我想要的是類似於$scope.team1.cy = 100之後的項目8.

我只是不能想出一個解決方案,我會說像ng-if如何工作,但不能得到它的工作ķ。

回答

2

你可以這樣寫:

<div ng-repeat="number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" ng-init="$index > 8 ? team1.cy = 100 : ''"> 
</div> 

ng-init將在每次迭代,我們可以檢查$index達到8然後我們遞增編號調用。你codepen例如

更新

來看,很顯然,我們不能直接改變team1.cy變量$index後,將其更新爲100達到8

所以,除非你想使用可變team1.cy別的地方,就可以解決您的問題是這樣的:

<circle ng-repeat="person in team1.members" 
    class="dotMap" 
    ng-click="mapCurrentPerson($event)" 
    fill="#232323" stroke="#232323" 
    stroke-miterlimit="10" 
    ng-attr-cx="{{$index * 40 + 40}}" 
    ng-attr-cy="{{ cyValue }}" 
    ng-init="cyValue = ($index > 8 ? 100 : 30)" 
    r="16.5" 
    ng-class="{selectedMap: current.name === person.name}" /> 

如果表達你ng-init越來越複雜,那麼我建議你在你的控制範圍寫一個函數是這樣的:

$scope.calculateCyValue = function($index) { 
    return ($index > 8 ? $index * 40 + 40 : $index * 40 + 40); 
}; 

,然後在HTML中使用它(現在你不需要ng-init):

<circle ng-repeat="person in team1.members" 
    class="dotMap" 
    ng-click="mapCurrentPerson($event)" 
    fill="#232323" stroke="#232323" 
    stroke-miterlimit="10" 
    ng-attr-cx="{{$index * 40 + 40}}" 
    ng-attr-cy="{{ calculateCyValue($index) }}" 
    r="16.5" 
    ng-class="{selectedMap: current.name === person.name}" /> 
+0

我明白了,但是當我打的8+項目的所有項目有100新的價值假設我有10個項目,前8個需要30個,最後2個需要100個,這是我想實現的結果。並感謝編輯我的拼寫^ – Dennis

+0

您是否將該屬性'ng-attr-cy'傳遞給相同的元素或添加了'ng-repeat'的元素的子元素? –

+0

這是我重複它的方式http://codepen.io/denniswegereef/pen/NxNGav – Dennis

0

您可以在索引傳遞給方法在你的虛擬機,並返回從那裏所需的值:

ng-attr-cy="{{vm.getValue($index)}}" 

vm.getValue = function(index){ 
    // do some magic with the index. 
    return myData[index]; 
}