Search code examples
javascriptangularjsangularjs-ng-repeatng-showangularjs-controlleras

ng-show angular tab with ng-repeat


I have been working on this for a while now and cannot figure out why it will not work. This is the effect I am trying to create- http://plnkr.co/edit/RAeIwFbn2Zoe9WfLdMX8?p=preview. I wish to have create a tab bar that when clicked on will show different information.

This is the code I have so far, but it will not work for some reason:

HTML

<ul class="nav nav-pills">
 <li ng-repeat="tablet in Packages.panelTabs">
    <a href ng-click="tab = tablet.tabNum"> 
      {{tablet.name}}
    </a>
 </li>
    <p ng-show="tab === 1"> Tab1 content </p>           
    <p ng-show="tab === 2"> Tab2 content</p> 
 </ul>

JS

My angular code looks like this.

this.panelTabs = [

            {
                name: "package-price",
                tabNum: 1
            },
            {
                name: "package-description",
                tabNum: 2
            }
        ];

I have read various answers and tried many things, but feel it must be something stupid I am missing. Any help would be greatly appreciated.

Thanks, Paul


Solution

  • While setting tab model do declare it in parent scope by using $parent keyword. The reason on each iteration ng-repeat directive does create a new prototypically inherited scope.

    Markup

    <li ng-repeat="tablet in Packages.panelTabs">
       <a href ng-click="$parent.tab = tablet.tabNum"> 
          {{tablet.name}}
       </a>
    </li>
    

    @azium suggested to use controllerAs because you are already using it by using Packages as alias of your controller. Now put tab variable inside your controller variable like Packages.tab

    Markup

    <li ng-repeat="tablet in Packages.panelTabs">
       <a href ng-click="Packages.tab = tablet.tabNum"> 
          {{tablet.name}}
       </a>
    </li>
    <p ng-show="Packages.tab === 1"> Tab1 content </p>           
    <p ng-show="Packages.tab === 2"> Tab2 content</p>