Ash
Ash

Reputation: 574

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?

Upvotes: 1

Views: 754

Answers (3)

z.a.
z.a.

Reputation: 2777

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>

Upvotes: 1

jfadich
jfadich

Reputation: 6348

Instead of keeping track of the current state name in the $rootScope why not check the state name directly like this.

ng-class="{ 'active': $state.includes('state.name')}"

This should work for nested states too. For example if your states look like below then $state.includes('home.item1') will be true if the state is subItem1

home
    item1
        subItem1

Upvotes: 0

Eugene
Eugene

Reputation: 3375

Your navigation function runs only once when page loads. And $rootScope.current is set only once. Looks like you are using ui-router. Try to put that line in $stateChangeSuccess event callback:

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams) {
    $rootScope.current = toState.name;
  }
)

Upvotes: 0

Related Questions