我正在使用 ng-repeat
重复一些项目,但是当 $index
达到某个数字时,我想更改 $scope
> 在该数字之后。
所以假设:我有一个 ng-repeat
并且我有这个属性:
ng-attr-cy="{{ team1.cy }}"
这在我的 Controller 中$scope.team1.cy = 30;
我想要的是,当 $index > 8
时,它会将 8 之后的项目的范围值更改为 $scope.team1.cy = 100
.
我只是想不出一个解决方案,我会说类似ng-if
如何工作但无法让它工作。
最佳答案
你可以这样写:
<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 示例,很明显,我们无法在 $index
达到 8 后直接更改 team1.cy
变量以将其更新为 100。
因此,除非您想在其他地方使用变量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
中的表达式变得复杂,那么我建议您在 Controller 作用域中编写一个函数,如下所示:
$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}" />
关于javascript - $index达到一定数字后更新a范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34335593/