Christopher Marshall
Christopher Marshall

Reputation: 10736

How to set class based on current route name/controller

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.

Upvotes: 28

Views: 20888

Answers (4)

ivanreese
ivanreese

Reputation: 2758

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.

Upvotes: 3

K&#233;nium
K&#233;nium

Reputation: 105

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;
});

Upvotes: 2

pavelgj
pavelgj

Reputation: 2701

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

Upvotes: 5

Valentyn Shybanov
Valentyn Shybanov

Reputation: 19391

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

Upvotes: 33

Related Questions