hussain hussain - 2 months ago 20
CSS Question

How to make navbar tab active or visited based on state using angular ui-router?

I want to make tab active based on current state, I want to set background color for the tab when state is active when user switch tab only visited or current active tab should be highlighted, is it something then can be achieved using ui-router ?

main.html

<nav class="navbar navbar-default">
<div >
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a ui-sref="app.dit">DIT</a></li>
<li><a ui-sref="app.st">ST</a>
<li><a ui-sref="app.uat">UAT</a></li>
<li><a ui-sref="app.prod">PROD</a></li>
</ul>
</div>
</div>
</nav>


app.js

angular.module('App', [
'ui.router'

]).config(function($stateProvider, $httpProvider, $urlRouterProvider) {
'use strict'
$urlRouterProvider.otherwise(function($injector) {
var $state = $injector.get('$state');
$state.go('app.dit');
});

$stateProvider
.state('app', {
abstract: true,
url: '',
templateUrl: 'web/global/main.html',
controller: 'MainCtrl'
})
.state('app.dit', {
url: '/dit',
templateUrl: 'view/partials/dit.html',
controller: 'DitCtrl'
})
.state('app.st', {
url: '/st',
templateUrl: 'view/partials/st.html',
controller: 'StCtrl'
})
.state('app.uat', {
url: '/uat',
templateUrl: 'view/partials/uat.html',
controller: 'UatCtrl'
})
.state('app.prod', {
url: '/prod',
templateUrl: 'view/partials/prod.html',
controller: 'ProdCtrl',
});

Answer

You could use ui-sref-active directive with className as its attribute value. So based on current active state it will apply active class over that particular li element.

<nav class="navbar navbar-default">
    <div >
        <div class="collapse navbar-collapse">
            <ul class="nav navbar-nav">
                <li ui-sref-active="active"><a ui-sref="app.dit">DIT</a></li>
                <li ui-sref-active="active"><a ui-sref="app.st">ST</a>
                <li ui-sref-active="active"><a ui-sref="app.uat">UAT</a></li>
                <li ui-sref-active="active"><a ui-sref="app.prod">PROD</a></li>
            </ul>
        </div>
    </div>
</nav>
Comments