Search code examples
javascriptangularjscordovaangularjs-ng-repeatsteroids

Angular JS going from static to ng-repeat


So I have the following code that shows a tab title, and when you click on it, a content area expands.

<!-- .accordion__tab -->
<div class="accordion__tab">
<div class="accordion__tab-title" ng-click="openTab('tab one')"><h3 class ="grey-text">Box 1</h3></div>
<div class="accordion__tab-content" ng-show="isOpenTab('tab one')">Tab content goes here!</div>
</div>
<!-- .accordion__tab -->
<div class="accordion__tab">
<div class="accordion__tab-title" ng-click="openTab('tab two')"><h3 class ="grey-text">Box 2</h3></div>
<div class="accordion__tab-content" ng-show="isOpenTab('tab two')">Tab content goes here!</div>
</div>

This works just fine, So as I am still trying to learn angular I am trying to put this in a loop so I can have 5 of these, so I originally put this code in.

<div ng-repeat="i in [1, 2, 3, 4, 5]">
    <div class="accordion__tab">
        <div class="accordion__tab-title" ng-click="openTab('tab')"><h3 class ="grey-text">Box {{i}}</h3></div>
        <div class="accordion__tab-content padding" ng-show="isOpenTab('tab')">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
    </div>
</div>

And this loops through, and makes 5 of thses objects, but the problem is if you click on one of them all of them expand (which makes sense because they all have the openTab('tab') instaed of unique tab identifiers. So! I tried to create them dynamically with openTab('tab {{i}}') like I did with the counter but it is not working. Nothing happens, any ideas on how I can dynamically change the tab name? Thanks!


Solution

  • This is because, all of your tabs have the same parameter / identifier in the openTab method..

    Change your code to

    <div ng-repeat="i in [1, 2, 3, 4, 5]">
        <div class="accordion__tab">
            <div class="accordion__tab-title" ng-click="openTab('tab_' + $index)"><h3 class ="grey-text">Box {{i}}</h3></div>
            <div class="accordion__tab-content padding" ng-show="isOpenTab('tab_' + $index)">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
        </div>
    </div>
    

    Since ng-click is an Angular method, you don't need the {{}} to resolve the value of i or $index.