Billy Assim
Billy Assim

Reputation: 227

Angular switching CSS class based on route?

I have the below HTML file:

<header ng-include="'app/partials/includes/header.html'"></header>

<div class="container" ng-controller="LoginCtrl">

</div>

The above is for the login page, the below is for the register:

<header ng-include="'app/partials/includes/header.html'"></header>

<div class="container" ng-controller="RegisterCtrl">

</div>

This is the header:

<div class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a href="#" class="navbar-brand">Curve</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li class="active"><a href="#/register">Sign Up</a></li>
                <li><a href="#/login">Sign In</a></li>
            </ul>
        </div>
    </div>
</div>

How can apply the .active class to the list element dependent upon the route?

If the route is /register, I want the active class applied, and same for login.

How can this be done in Angular?

Upvotes: 2

Views: 1333

Answers (1)

chubbsondubs
chubbsondubs

Reputation: 38676

Use ng-class on any element to conditionally apply to an element. Using the object notation the key is the class name, and the value is an expression when evaluates to true the class is added to that element's class attribute.

<div class="header" ng-controller="HeaderController">
  <div ng-class="{ active: registrationOrLogin }">

</div>

And in a controller:

app.controller("HeaderController", [ "$scope", "$location", function($scope, $location) {
    $scope.registrationOrLogin = $location.hash() == "/login" || $location.hash() == "/registration";
} ] );

Upvotes: 3

Related Questions