How to set class based on current route name/controller

时光毁灭记忆、已成空白 提交于 2019-12-20 16:23:12

问题


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


来源:https://stackoverflow.com/questions/14220244/how-to-set-class-based-on-current-route-name-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!