Search code examples
javascripthtmlangularjstabsng-class

Set default tab to Angular.js tabs


I have an Angular.js component which has a list of tabs. When a tab is clicked I assign an ng-classto it (active), so it gets highlighted. This is working fine, but I also want the first tab to be the default active one when a user first load the page, but at the moment nothing is highlighted when I load the page.

Here's my component:

'use strict';

angular.module('menuBar').component('menuBar', {
    templateUrl: 'menu-bar/menu-bar.template.html',
    controller: function menuBarController() {
        this.menus = [
            {
                name: 'Tab1'
            }, {
                name: 'Tab2'
            }, {
                name: 'Tab3'
            }, {
                name: 'Tab4'
            }, {
                name: 'Tab5'
            }
        ];

        this.tab = this.menus[0].name;

        this.setTab = function (tabId) {
            this.tab = tabId;
        }

        this.isSet = function (tabId) {
            return this.tab === tabId;
        }
    }
});

Here my html template:

<div class="navbar navbar-inverse navbar-collapse">
    <div class="container">   
        <ul class="nav nav-tabs">
            <li ng-repeat="menu in $ctrl.menus" ng-class="{active:tab.isSet(menu.name)}">
                <a href ng-click="tab.setTab(menu.name)">{{menu.name}}</a>
            </li>
        </ul>  
    </div>
</div>

Maybe something wrong at this line here where I'm trying to set my default tab?

this.tab = this.menus[0].name;

Update: Plunker added

Live preview here


Solution

  •  <div class="navbar navbar-inverse navbar-collapse">
    <div class="container">   
        <ul class="nav nav-tabs">
            <li ng-repeat="menu in $ctrl.menus" ng-class="     active:menu.name==$ctrl.tab}">
                <a href ng-click="$ctrl.setTab(menu.name)">{{menu.name}}</a>
            </li>
        </ul>  
    </div>