我需要在其范围之外的 ng-repeat 指令中使用 $index 的值。我尝试了几种解决方法,但没有成功。
这是我的代码:
<tbody ng-init="countObj={"count":0}" >
<tr ng-repeat="data in result.data1" ng-init="index1 = $index" ng-if='result.data1'>
<td>{{countObj.count = index1+1}}</td> // here I assing index1 to parent scope count
<td>{{data}}{{countObj.count}}</td> // here count has the correct value
<td>{{result.data2[$index]}}</td>
</tr>
<tr ng-repeat="data in result.data3" ng-init="index2 = $index" ng-if='result.data3'>
<td>{{index2+countObj.count}}</td> // here I add count to index2
<td>{{result.data3[$index]}}{{countObj.count}}</td> // here count has no value
<td>{{result.data4[$index]}}</td>
</tr>
<tr ng-if='result.data1 == undefined && result.data3 == undefined'>
<td><strong>No data to display.</strong></td>
</tr>
</tbody>
这个完整的表格在我刚刚发布的 tbody 标签的自定义指令中。
指令如下:
<concept-details ng-repeat = "result in searchRes.list"></concept-details>
数据呈现得非常好,只是我无法在第二个 tr 标记中获取计数。
我在 w3school 上测试了上述解决方法,它工作正常。 这是我测试的代码:
<table>
<thead>
<tr>
<th>S No.</th>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody ng-init="count" >
<tr ng-init="test = 5">
<td>test is</td>
<td>{{count = test}}</td>
<td>end</td>
</tr>
<tr ng-init="test2 = 10">
<td>test 2 is</td>
<td>{{count + test2}}</td>
<td>end</td>
</tr>
</tbody>
</table>
我是 angularjs 的新手,所以请原谅我可能犯的任何错误。
非常感谢任何建议。
提前致谢。
编辑:代码更改为 Naveen Kumar 的建议,但输出仍然相同
最佳答案
对于 ng-repeat 范围创建工作不同。 对于每个循环,ng-repeat 创建一个新的范围,它继承自父级 但这里有一个陷阱 如果该属性在您的情况下是原始的,它只是在子范围内创建一个副本。 ng-repeat的代码如下
childScope = scope.$new();
childScope[valueIdent] = value;
计数($scope) 复制到 计数复制($childScope)
因此,您的 count 属性的增量是在 count 的本地副本上完成的 在你的第一个循环中。
因此,您所有的增量都不会反射(reflect)在您范围内的主要计数中。 解决方法是将计数作为对象内的属性。 如果将其更改为对象属性,则会生成对象的副本 仍然会引用相同的主计数属性。
countObj ($范围) 复制到 countObjCopy($childScope)
countObj 和 countObjCopy 都引用相同的属性 count
//while initializing
<tbody ng-init="countObj={"count":0}" >
//while incrementing
<td>{{countObj.count= index1+1}}
在进一步深入研究时,似乎存在的问题多于由于创建子作用域而引起的问题。我对问题发表了评论,它与 Angular 更相关 View 渲染中更新范围变量导致的无限摘要错误。 更多信息请引用此处 https://docs.angularjs.org/error/ $rootScope/infdig
所以最好的方法是在 View 内容之外更新 count obj
解决方法之一是使用如下方法在第一个循环本身的init中更新countobj的计数并使用索引显示
<tbody ng-init="countObj={'count':result.data1.length}" >
<tr ng-repeat="data in result.data1" ng-init="index1 = $index" ng-if='result.data1'>
<td>{{index1+1}}</td> // here I assing index1 to parent scope count
<td>{{data}}{{index1+1}}</td> // here count has the correct value
<td>{{result.data2[$index]}}</td>
</tr>
<tr ng-repeat="data in result.data3" ng-init="index2 = $index" ng-if='result.data3'>
<td>{{index2+countObj.count+1}}</td> // here I add count to index2
<td>{{result.data3[$index]}}{{countObj.count}}</td> // here count has no value
<td>{{result.data4[$index]}}</td>
</tr>
</tbody>
关于javascript - 在 angularjs 中使用 ng-repeat 时扩展 $index 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28847752/