How to set class based on current route name/controller

All we need is an easy explanation of the problem, so here it is.

Trying to set a class based on my current controller or current route (URL Segment 1).

something like

<body class="{{controllerName}}">

That way in case I need to target separate pages for CSS specificity, it makes it easy.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

My solution would be: subscribe to route changes at route scope and put name of the controller there:

app.run(function($rootScope) {
   $rootScope.$on('$routeChangeSuccess', function(ev,data) {   
     if (data.$route && data.$route.controller)
       $rootScope.controller = data.$route.controller;
   })
});

Check Plunker solution

Method 2

You can use the $route service, it has current property which will give you current controller.

Method 3

Even simpler. There’s a controller property directly on the data argument.

$rootScope.$on("$routeChangeSuccess", function(e, data) {
    $rootScope.controller = data.controller;
});

As best as I can tell, the data argument is the same object as $route.current. The controller property is in the prototype for that object.

Method 4

For the version 1.3 of Angular, you can use this piece of code :

$rootScope.$on('$routeChangeSuccess', function (ev, data) {
    if (data.$$route && data.$$route.controller)
        $rootScope.controller = data.$$route.controller;
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply