gpt4 book ai didi

javascript - 在 $index 达到一定数量后更新范围值

转载 作者:行者123 更新时间:2023-11-29 21:37:55 27 4
gpt4 key购买 nike

我正在使用 ng-repeat 重复一些项目,但是当 $index 达到某个数字时,我想更改 $scope 在那个数字之后。

假设:我有一个 ng-repeat 并且我有这个属性:

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

这在我的 Controller 中 $scope.team1.cy = 30;

我想要的是当 $index > 8 时,它将范围的值更改为类似 $scope.team1.cy = 100 的值,用于 8 之后的项目.

我只是想不出一个解决方案,我会说一些类似 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例子,很明显我们不能直接修改team1.cy变量,在$index达到8后将其更新为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 达到一定数量后更新范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34335593/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com