maurya8888
maurya8888

Reputation: 253

ngClass not updating the class

I am using angularJS with bootstrap to design a navigation on my application. I have defined a main controller and inside the main controller I call different page views using the ng-view attribute and then these individual views have their own controllers.

I am using the ng-class attribute to add the active class to my links, however, it is not working. The expression evaluates to true or false but the ng-class does not updates the class="active" on the elements.

On my home page I have the following code -

<section ng-controller="dashBoardCtrl" class="container">
        <section class="row">
            <h1>DME DashBoard | <small>WFM HeadCount</small> </h1>
        </section>

        <section class="row">
            <ul class="nav nav-tabs">
                <li role="presentation" ng-class="{active: {{path=='/'}}}"><a ng-href="#/">Home</a></li>
                <li role="presentation" ng-class="{active: {{path=='/login'}}}"><a ng-href="#/login">Login</a></li>
            </ul>
        </section>

        <section ng-view></section>
    </section>

This is how the routes are configured on the app -

dmeDash.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: '/views/home.html',
            controller: 'homePageCtrl'
        })
        .when('/login', {
            templateUrl: '/views/login.html',
            controller: 'loginCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
}]);

The dashBoardCtrl have the following code -

dmeDashControllers.controller('dashBoardCtrl', ['$scope','$location', function($scope, $location) {

    $scope.path = $location.$$path;

    $scope.$watch('path',function(n,o) {

    })

}]);

Home Page Controller has the following code -

dmeDashControllers.controller('homePageCtrl', ['$scope','$location', function($scope, $location) {

    $scope.$parent.path = $location.$$path;
}]);

The log in page controller has the following code -

dmeDashControllers.controller('loginCtrl', ['$scope','$location', function($scope, $location) {

    $scope.$parent.path = $location.$$path;

}]);

When I click from Home page to Login page the active class is not removed from home page link and not applied to the login page as well, however, when I view the code in firebug the expressions evaluates to true or false when the page changes.

When I refresh on individual pages the ng-class works correctly but not when using the hyperlinks, please suggest.

Upvotes: 2

Views: 2124

Answers (1)

Raulucco
Raulucco

Reputation: 3426

The syntax is wrong on the template. It should be:

 <li role="presentation" ng-class="{'active': path==='/'}"><a ng-href="#/">Home</a></li>

And as style guide try using the === instead of the simple == because of type coercion. Or test agains truthy or falsy

Upvotes: 4

Related Questions