Add / remove css class on route change in angularjs

I'm not sure how this can be achieved in Angular. I want to add and remove CSS class on route change. I am trying to show and hide a vertical menu. I am currently using ui-route. Any suggestion or link to an example would be highly appreciated or any other suggestion for a different approach to my problem is also appreciated

+3


source to share


3 answers


The easiest and most efficient way:

angular.module(...).run(function($rootScope, $state) {
  $rootScope.$state = $state;
});

<div ng-if="$state.contains('someState')">...</div>

      

This will remove the DOM which will improve performance if there are many bindings in the menu.

However, I keep telling people to consider using the named views for navigation:

<body>
  <nav ui-view="nav"></nav>
  <div class="container" ui-view></div>
</body>

$stateProvider.state('home', {
  views: {
    'nav@': {
       templateUrl: 'nav.html'
     }
     '': {
       // normal templateUrl and controller goes here.
     }
  }
});

      



The cool part about this is that child states can override and control which navigation file to use, and can even customize sections and controllers that share data between navigation and content. No directives / services required!

Finally, you can also do this:

<nav ng-show="$state.contains('somestate')"></nav>
<nav ng-class="{someClass:$state.contains('somestate')}"></nav>

      

Alternative check ui-sref-active

All my suggestions primarily assume that you are using the UI-Router as this is the best!

+3


source


Try the following:



app.run(function ($rootScope) {
  $rootScope.$on("$stateChangeStart", function(event, toState, fromState){

    if (toState.url === "/path") {
        $('div').addClass('className');
    } else {
        $('div').removeClass('className');
    }

  });
});

      

+2


source


You can register the changed route and add this css to your DOM:

$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
     // Add your logic, for instance:
     $('body').addClass('hide-menu');
});

      

Obviously events were affected before the route was changed: "$ locationChangeStart", here .
/ Edit / - Improved approach
Also I would rather use the ng-class attribute and just bind a specific value from your main controller.

app.controller('MainController', function ($scope) {
    $scope.toggleMenu = function(isToShow) {
        $scope.isVisibleMenu = isToShow == true;
    }; 
});

      

then in your html:

<!-- Menu toggle button-->
<button ng-click="toggleMenu()"></button>

<div class="toggleable-menu" ng-class="{'visible-menu': isVisibleMenu}">
<!-- The menu content-->
</div>

      

and the simplest CSS way (you can probably add animation or whatever to toggle this menu.)

.toggelable-menu {
    display: none;
}

.toggelable-menu.visible-menu {
    display: block;
}

      

+1


source







All Articles