javascriptangularjsangular-ui-bootstrapangular-ui-bootstrap-tab

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


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' ?


Solution

  • 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.