adding or removing classes based on route changes in angular

痴心易碎 提交于 2019-12-01 08:48:41

This can be achieved using ng-class. Just make use of $location in your controller. This example is quite simple. Here we add an active class to div when $location.path() equals '/'.

Then we setup a conditional ng-class in our view that adds the active class.

View

<div ng-class="{active: location === '/'}">
  <p>The parent DIV will have active class added when location path equals '/'</p>
</div>

Controller

.controller('MainCtrl', function ($scope, $rootScope, $location) {
    $scope.location = $location.path();
    $rootScope.$on('$routeChangeSuccess', function() {
        $scope.location = $location.path();
    });
});

Since you tagged your question with angular-ui-router I assume you are using it.

Using UI routers ui-sref combined with ui-sref-active will let you assign a class for the currently active state (or any child states).

Here for example. If state is app.tab1 (or a child state) the active class will be applied to the li element.

<ul>
  <li ui-sref-active='active'>
    <a ui-sref="app.tab1">link</a>
  </li>
  <li ui-sref-active='active'>
    <a ui-sref="app.tab2">link</a>
  </li>
  <li ui-sref-active='active'>
    <a ui-sref="app.tab3">link</a>
  </li>
</ul>

See http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active

You can use ng-class

Please read the documentation

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