[英]ng-init Used Twice Inside ng-repeat, Only First ng-init is Being Evaluated
See the below code:请参阅以下代码:
<tr ng-repeat="x in [].constructor(6) track by $index" ng-init="loopNumber = $index">
<td class="border-right" style="width:10%;" ng-init="day = monthOfData[7 * loopNumber]">
<p>{{day}}</p>
</td>
<td class="border-right" style="width:10%;" ng-init="day = monthOfData[7 * loopNumber+1]">
<p>{{day}}</p>
</td>
</tr>
I expect where {{day}} is being used, the output would be something like:我希望在哪里使用 {{day}},output 将类似于:
1
2
However, the output is:但是,output 是:
1
1
AngularJS seems to be skipping the second use of ng-init inside the ng-repeat. AngularJS 似乎在 ng-repeat 中跳过了 ng-init 的第二次使用。 Is this a performance feature of AngularJS?
这是 AngularJS 的性能特征吗? I am using ng-init to save re-evulating the same expression.
我正在使用 ng-init 来保存重新评估相同的表达式。
This is not a bug, this usage of ng-init
is wrong.这不是错误,
ng-init
的这种用法是错误的。 To initialize means to set the start value of a variable, so with your last use of ng-init
you're initializing a variable that already has a value and "overwriting" what was already there.初始化意味着设置变量的起始值,因此在您最后一次使用
ng-init
时,您正在初始化一个已经具有值的变量并“覆盖”已经存在的变量。
In more detail: The first instance of ng-init
sets loopNumber = 0
because arrays and indexes start with 0, not 1. Then you set day = 0
-- at that point, both instances of {{day}}
in your html would evaluate to 0. Then lastly you set day = 1
, therefore the output of {{day}}
becomes 1.更详细地说:
ng-init
的第一个实例设置loopNumber = 0
,因为 arrays 和索引以 0 开头,而不是 1。然后你设置day = 0
0——此时,html 中{{day}}
的两个实例都会评估为 0。然后最后设置day = 1
,因此{{day}}
的 output 变为 1。
Note that this applies to all the places in your page where you used {{day}}
, not just the lines after the third ng-init
.请注意,这适用于页面中您使用
{{day}}
的所有位置,而不仅仅是第三个ng-init
之后的行。 There are only a few appropriate uses of ng-init
(such as aliasing special properties of ng-repeat
) and this is not one of those cases. ng-init
只有少数适当的用途(例如别名ng-repeat
的特殊属性),这不是其中一种情况。
An example of how the code could work without ng-init
:代码如何在没有
ng-init
的情况下工作的示例:
<tr ng-repeat="x in [].constructor(6) track by $index">
<td>
<p>{{ monthOfData[7 * $index] }}</p>
</td>
<td>
<p>{{ monthOfData[7 * $index + 1] }}</p>
</td>
</tr>
Or alternatively, since your td
blocs are very similar, we could add a second loop like so:或者,由于您的
td
块非常相似,我们可以像这样添加第二个循环:
<tr ng-repeat="x in [].constructor(6) track by $index" ng-init="loopNumber = $index">
<td ng-repeat="x in [].constructor(2) track by $index" ng-init="var = $index">
<p>{{ monthOfData[7 * loopNumber + var] }}</p>
</td>
</tr>
Note how in this second example ng-init
is used to alias the two instances of $index
referring to the two different loops.请注意,在第二个示例中,
ng-init
如何为引用两个不同循环的$index
的两个实例起别名。 This was not needed in the first example and we can use $index
directly when evaluating the expressions.这在第一个示例中不需要,我们可以在评估表达式时直接使用
$index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.