2014-09-23 42 views
2

我已經在angularjs中創建了一個應用程序,這裏我有一個表,我試圖把一個動態id放在一個超鏈接的ng-init中生成動態id,應用程序工作正常,但計數不增加count在ng-repeat內不遞增

誰能告訴這個

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> 

回答

2

您可以創建一個指令,跟蹤全局計數的閉包,並在每次鏈接函數運行到範圍時公開唯一的id。

directive('uniqueId',function(){ 

    var count=0; 

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

和標記

看到這個running example

+0

但表格ID不正確 – 2014-09-23 12:36:21

+0

{{places.id}}在表格元素的id屬性上更改{{count}} – laurent 2014-09-23 12:38:45

+0

嘿,這很好用......謝謝 – 2014-09-23 12:49:11

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> 
一些解決方案

試試這個不知道

+0

都能跟得上我希望有一個獨特的動態ID,你不能指定$指數 – 2014-09-23 12:14:23

+0

更新我的回答,請檢查 – 2014-09-23 12:21:57

+0

使其可根據$指數。例如,如果你想像101,102,103 ..那麼你可以通過getClick($ index + 101) – masum7 2014-09-23 12:22:11

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> 
+0

看到我想要唯一的ID ,如果你看到有地方1和地點3將有相同的索引,當你點擊http://jsfiddle.net/g24tp0op/1/ – 2014-09-23 12:16:43

0

你總是可以擺脫ng-init="count++"{{getUniqueIndex()}}取代{{count}}。在你的控制器範圍內,你可以定義一個函數getUniqueIndex,它返回你所需要的。這還有一個好處,那就是在控制器中保留這個邏輯,你可能更多地使用它。

+0

,但如何分配到表ID,因爲會有多個表格右鍵 – 2014-09-23 12:28:15

+0

您需要跟蹤他們的模型。一個想法是2D陣列。 – AlexMA 2014-09-23 12:35:20

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>