28

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.

Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94

4 Answers4

33

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

Valentyn Shybanov
  • 19,331
  • 7
  • 66
  • 59
  • Thanks! Made some slight edits as data.$route.controller was changing based on some tab controllers I had initiated. Just need the parent controller. – Christopher Marshall Jan 08 '13 at 18:07
  • 12
    it's data.$$route.controller in 1.0.7 – vortex Sep 11 '13 at 13:17
  • 1
    Note that properties starting with [$$ prefix are considered private](http://docs.angularjs.org/tutorial/step_05) and are accessed or modified at your own risc (since they might change between versions of AngularJS). – Strille Jan 21 '14 at 13:52
  • Any idea why data.$route would be undefined? Valentyn, I have placed your code in my main Angular file, where routeProvider is also configured. routeChangeSuccess _is_ being fired. – Sam Feb 15 '14 at 17:57
  • if you use ui-router, I think it should be data.$$route instead of data.$route I guess – sean May 28 '15 at 03:50
  • @NicolaMarcacciRossi still here: https://docs.angularjs.org/api/ngRoute/service/$route#$routeChangeSuccess – Valentyn Shybanov Nov 20 '15 at 06:16
5

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

pavelgj
  • 2,246
  • 11
  • 13
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.

ivanreese
  • 2,718
  • 3
  • 30
  • 36
2

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;
});
Kénium
  • 105
  • 1
  • 10
  • 1
    Using $$ properties is not recommended, as they are internal to Angular, not part of the public API, and are likely to be changed or broken in future updates. From the docs (https://docs.angularjs.org/tutorial/step_05#-prefix-naming-convention): "If you inspect a Scope, you may also notice some properties that begin with $$. These properties are considered private, and should not be accessed or modified." – ivanreese Sep 24 '14 at 01:28