Search code examples
javascriptangularjsangular-ui-routerurl-routingangularjs-routing

Angular adding a body class depending on state


I have something like this working

  <body ng-app="ELT" ng-class="{'mapBody': $state.includes('map')}" ng-controller="mainCtrl">

So obviously what I am trying to do is add a class "mapBody" when the state is map

and my controller a such

  .controller('mainCtrl', ['$scope','$state',function ($scope,$state) {
    'use strict';
    $scope.$state = $state;
  }])

Is there a better way to do this ? Don't like the fact I had to had a new controller just for this one thing, plus it's a lot of logic in the html.


Solution

  • As per Radim Kohler Better way is, you could use the ui-sref-active directive.

    To add the class active to your element when the ui-router state matches use

    HTML

    <body ng-app="ELT" ui-sref-active="mapBody" ng-controller="mainCtrl">
      <a ui-sref="app"></a>
    </body>
    

    Whenever underlying ui-sref is current state then if will apply mapBody class to body.

    See Example here

    Edit

    In your case you want to append a class to body depending on state, So using ui-sref-active in this case will not work. Because body can contain several ui-sref and at least one will be satisfied, class will always append to body. I believe currently the way you are doing is correct. But I'd like to suggest one change, instead of assigning $state to controller each time. Do it in angular run phase only once.

    //it will assign a state inside $rootScope and it will get available on each page 
    app.run(function($rootScope, $state) { 
      $rootScope.$state = $state;
    });
    

    Above code will be more cleaner and it will avoid assigning $state inside scope each time.

    Thanks.