如何在ng-class中创建迭代次数/计数器

时间:2016-06-17 06:00:31

标签: angularjs

如何在ng-class中实现迭代? ,下面是我的代码

 <div class="list-message">
      <ul>
        <li ng-repeat="mainList in itemsList" ng-class="{ active: isSet(i++)}" >
          <a href ng-click="setTab(i++) " ng-repeat="x in mainList">
            {{x.message_text}}
          </a>
        </li>
      </ul>
     </div>

   <div class="detail-message">
    <ul ng-repeat="mainList in itemsList track by $index" ng-show="isSet(i++)">
      <li ng-repeat="x in mainList">
        {{x.message_detail}}
      </li>
    </ul>
   </div>

我想要的结果就像下面的例子.ng类中的迭代将是计数迭代次数。

  <div class="list-message">
     <ul>
      <li ng-repeat="mainList in itemsList" ng-class="{ active: isSet(1)}" >
         <a href ng-click="setTab(1) " ng-repeat="x in mainList">
            {{x.message_text}}
          </a>
       </li>

      <li ng-repeat="mainList in itemsList" ng-class="{ active: isSet(2)}" >
        <a href ng-click="setTab(2) " ng-repeat="x in mainList">
          {{x.message_text}}
         </a>
       </li>

       <li ng-repeat="mainList in itemsList" ng-class="{ active: isSet(3)}" >
         <a href ng-click="setTab(3) " ng-repeat="x in mainList">
           {{x.message_text}}
         </a>
       </li>
     </ul>
    </div>

   <div class="detail-message">
    <ul ng-repeat="mainList in itemsList track by $index" ng-show="isSet(1)">
      <li ng-repeat="x in mainList">
        {{x.message_detail}}
      </li>
    </ul>
    <ul ng-repeat="mainList in itemsList track by $index" ng-show="isSet(2)">
      <li ng-repeat="x in mainList">
        {{x.message_detail}}
      </li>
    </ul>
    <ul ng-repeat="mainList in itemsList track by $index" ng-show="isSet(3)">
      <li ng-repeat="x in mainList">
        {{x.message_detail}}
      </li>
    </ul>
   </div>

谢谢你,感谢你的每一条评论和帮助。

2 个答案:

答案 0 :(得分:1)

使用$ index跟踪ng-repeat中的索引

<ul>
<li ng-repeat="mainList in itemsList track by $index" ng-class="{ active: isSet($index)}" >
<a href ng-click="setTab($index) " ng-repeat="x in mainList">
{{x.message_text}}
</a>
</li>
</ul>

答案 1 :(得分:1)

使用$ index将帮助您跟踪索引。 $ index是重复元素(0..length-1)的迭代器偏移量。

你可以像使用它一样使用它。

 <li ng-repeat="mainList in itemsList" ng-class="{ active: isSet($index)}" >
     <a href ng-click="setTab($index) " ng-repeat="x in mainList">
       {{x.message_text}}
     </a>
   </li>