在ng-repeat中,count不会递增

时间:2014-09-23 12:10:47

标签: javascript angularjs ng-repeat

我在angularjs中创建了一个应用程序,这里我有一个表,我试图放置一个动态id,其中动态id是在超链接中的ng-init内生成的,应用程序工作正常但是计数没有递增

任何人都可以告诉我们这个

的解决方案

Working Demo

<div ng-app="Test1">
    <div ng-controller="Foo">
      <span ng-repeat="section in sectionData.sections">
       <span ng-repeat="regions in section.regions">
         <span ng-repeat="places in regions.places">
             <a ng-init="count++" href="javascript:void(0);" ng-click="getClick(count)">Click</a>
                <table id="{{count}}" border="1">
                      <tr><td>{{places.placeName}}</td></tr>
                </table>
         </span>
        </span> 
       </span>
    </div>
 </div>

5 个答案:

答案 0 :(得分:2)

您可以创建一个指令,该指令在全局计数的闭包中跟踪,并在每次链接函数运行到范围时公开增加的唯一ID。

directive('uniqueId',function(){

    var count=0;

    return {
        scope:{
            uniqueId:'='
        },
        link:function(scope, element, attr){
         count+=1;
        scope.uniqueId=count;
        }
    };
});

和标记

<a unique-id="places.id" href="javascript:void(0);" ng-click="getClick(places.id)">Click</a>

请参阅此running example

答案 1 :(得分:1)

id是否需要是int?

<div ng-app="Test1">
    <div ng-controller="Foo">
      <span ng-repeat="section in sectionData.sections" ng-init="id1 = $index">
       <span ng-repeat="regions in section.regions"  ng-init="id2 = id1 + '-' + $index">
         <span ng-repeat="places in regions.places" ng-init="id3 = id2 + '-' + $index">
             <a href="javascript:void(0);" ng-click="getClick(id3)">Click</a>
                <table id="{{id3}}" border="1">
                      <tr><td>{{places.placeName}}</td></tr>
                </table>
         </span>
        </span> 
       </span>
    </div>
 </div>

答案 2 :(得分:0)

<a ng-init="count" href="javascript:void(0);" ng-click="getClick(count)">Click</a>
            <table id="{{count = count+1}}" border="1">
                  <tr><td>{{places.placeName}}</td></tr>
            </table>

尝试这个不确定

答案 3 :(得分:0)

count替换为$index

            <a href="javascript:void(0);" ng-click="getClick($index)">Click</a>
            <table id="{{$index}}" border="1">
                  <tr><td>{{places.placeName}}</td></tr>
            </table>

答案 4 :(得分:0)

您可以随时摆脱ng-init="count++"并将{{count}}替换为{{getUniqueIndex()}}。在控制器范围中,您将定义一个函数getUniqueIndex,它返回您需要的内容。这样做的另一个好处是可以将控制器中的逻辑保留在您可能正在使用它的位置。

相关问题