How to set class based on current route name/contr

2019-03-17 06:22发布

问题:

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.

回答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



回答2:

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



回答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.



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