Set active tab style with AngularJS

One way of doing this would be by using ngClass directive and the $location service. In your template you could do:

ng-class="{active:isActive('/dashboard')}"

where isActive would be a function in a scope defined like this:

myApp.controller('MyCtrl', function($scope, $location) {
    $scope.isActive = function(route) {
        return route === $location.path();
    }
});

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/KzAfG/

Repeating ng-class="{active:isActive('/dashboard')}" on each navigation tab might be tedious (if you've got many tabs) so this logic might be a candidate for a very simple directive.


A way to solve this without having to rely on URLs is to add a custom attribute to every partial during $routeProvider configuration, like this:

$routeProvider.
    when('/dashboard', {
        templateUrl: 'partials/dashboard.html',
        controller: widgetsController,
        activetab: 'dashboard'
    }).
    when('/lab', {
        templateUrl: 'partials/lab.html',
        controller: widgetsController,
        activetab: 'lab'
    });

Expose $route in your controller:

function widgetsController($scope, $route) {
    $scope.$route = $route;
}

Set the active class based on the current active tab:

<li ng-class="{active: $route.current.activetab == 'dashboard'}"></li>
<li ng-class="{active: $route.current.activetab == 'lab'}"></li>