You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AngularJS的ng-repeat循环中重新初始化ng-init变量

解决AngularJS循环的条件判定问题

根据你描述的预期输出和迭代逻辑,我们先拆解整个流程的关键节点:
初始值 c=1,一共需要4次迭代:

  • 第1-3次迭代:输出「当前c的值」到「c+10」,然后把c增加10(从1→11→21→31)
  • 第4次迭代:直接输出当前的c值(31),不再更新c

结合这个逻辑,我们可以对应到你代码中需要填充的条件:

1. 前3次迭代的<some other condition>条件

这个条件需要在c还没到31的时候成立,或者根据迭代次数判断,两种方式都可行:

  • 用迭代索引(假设用ng-repeat的$index,索引从0开始):
    <!-- <some other condition> 替换为 -->
    $index < 3
    
  • 用c的当前值:
    <!-- <some other condition> 替换为 -->
    c < 31
    

2. 最后一次迭代的<some condition>条件

这个条件需要在第4次迭代时成立:

  • 用迭代索引:
    <!-- <some condition> 替换为 -->
    $index === 3
    
  • 用c的当前值:
    <!-- <some condition> 替换为 -->
    c === 31
    

3. 更新c值的条件

只有前3次迭代需要更新c,所以条件和<some other condition>一致即可:

<!-- 更新c的条件判断 -->
ng-if="$index < 3" ng-init="c +=10"

完整示例代码

这里给出一个用ng-repeat实现的完整可运行示例:

<div ng-app="" ng-init="c=1">
  <div ng-repeat="i in [1,2,3,4]">
    <!-- 前3次输出范围 -->
    <span ng-if="$index < 3">{{c}} to {{c+10}}</span>
    <!-- 最后一次输出单独值 -->
    <span ng-if="$index === 3">{{c}}</span>
    <!-- 前3次更新c的值 -->
    <span ng-if="$index < 3" ng-init="c +=10"></span>
  </div>
</div>

运行这段代码就能得到你预期的输出:1 to 11 11 to 21 21 to 31 31

内容的提问来源于stack exchange,提问作者lazy rabbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:47:08