angular ui bootstrap tabs component: how to get the content of a tab when the tab is active not clicked

2.8k views Asked by At

I am using the ui bootstrap 'tabs' component in my angularjs project. It is defined in a file called tab.html. the definition code is as follows :

<uib-tabset class="product-tab-bar">
    <uib-tab ng-repeat="tab in tabs" active="tab.active" ui-sref="{{tab.action}}" disable="tab.disabled" class="product-tab">
        <uib-tab-heading>
            <span class="{{tab.icon}}"></span> {{tab.title}}
        </uib-tab-heading>
        <div ui-view></div>
    </uib-tab>
</uib-tabset>

The tabs are defined in a controller, which are:

.controller('myController', function () {

    $scope.tabs = [
        {title: "tab1", action:".tab1" , icon: "icon-tab1", active: false},
        {title: "tab2", action:".tab2" , icon: "icon-tab2", active: true},
        {title: "tab3", action:".tab3" , icon: "icon-tab3", active: false}
    ]
});

the states definition are:

.state('tab', {
    url: '/tab',
    templateUrl: 'tab.html'
})
.state('tab.tab1', {
    url: '/tab1',
    templateUrl: 'tab1.html',
})
.state('tab.tab2', {
    url: '/tab2',
    templateUrl: 'tab2.html',
})
.state('tab.tab3', {
    url: '/tab3',
    templateUrl: 'tab3.html',
})

When you click the tab, the state will be changed. Now my question is, when I first load the tab.html, the tab 'tab2' is activated, but the content of tab2 is not loaded

you can see as below:

fist load tab2 content

I need to click on 'tab2', and the state will be changed and the content will be loaded

you can see as below:

after click tab2 content

So is there any method when I first load the tab.html, the content of 'tab2' can be loaded or how to active the state of 'tab2' ?

3

There are 3 answers

1
Szabolcs Dézsi On BEST ANSWER

You actually have to navigate to the state.

var activeTab;
for(var i = 0; i < $scope.tabs.length; i++) {
    if($scope.tabs[i].active) {
        activeTab = $scope.tabs[i];
        break;
    }
}

if(activeTab) {
    $state.go(activeTab.action);
}

JSFiddle available here.

0
Ori Damari On

That's because you change the state only on click (ui-sref="...")

So in the first time the tab is active but the ui-view don't change.

One quick solution for example is to $state.go to the active tab on first load.

0
faiyaz syed On

Use $state.go('the-state-name-in-quotes') method to trigger appropriate state and load content. Add this method in your controller.

Below documentation have more details

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options