Search code examples
javascriptangularjsng-class

ng-class condition works, but only when I refresh the page


I have a directive for Navigation; which is working fine... except when I change the page the class "active" is not getting added to the relevant link until I manually refresh the website.

The code where my ng-class is in :

<ul class="nav navbar-nav">
   <li ng-repeat="item in nav" ng-class="{'active':(item.alias==current)}">
      <a ui-sref="{{item.alias}}">{{item.name}}</a>
   </li>
</ul>

Navigation Directive:

(function () {
    'use strict';
    angular
        .module('app')
        .directive('navigation', navigation);

    navigation.$inject = ['$rootScope', '$timeout', '$state', 'navService'];

    function navigation($rootScope,$timeout, $state, navService) {

        $rootScope.nav = navService.nav;
        $rootScope.current = $state.current.name;

        return {
            restrict: 'AE',
            replace: 'true',
            templateUrl: '/layout/navigation/navigation.html'
        };

    };
})();

I was under the impression that this should work out of the box! Is it because I'm using the directive?


Solution

  • Most likely -not sure which version you are using, but...- you can use the ui-sref-active attribute in ui-router for this.

    <ul class="nav navbar-nav">
       <li ng-repeat="item in nav" ui-sref-active="active">
          <a ui-sref="{{item.alias}}">{{item.name}}</a>
       </li>
    </ul>