Different body backgrounds for different user interface states

In a simplified scenario, I have two UI-Router interface states , and they need different background colors for the background.

Ideally, I would like to do the following:

<body ng-class="background" ui-view> </body> 

and then in the controller for the states background classes are set (which can be dynamic, which means: it is calculated in the controller):

 stateHelperProvider .state({ name: 'a', url: '/a', templateUrl: 'views/a.html', controller: function ($scope) { $scope.background = 'bg1'; } }) .state({ name: 'b', url: '/b', templateUrl: 'views/b.html', controller: function ($scope) { $scope.background = 'bg2'; } }); 

But adding the ui-view attribute to the body removes it. So I have to put the ui-view attribute in a div inside the body.

 <body> <div ui-view></div> </body> 

How can I control the background of the body now?

I am aware of various hacks (for example, accessing the property of the DOM class of the body in the onEnter UI-Router function, ...), but is there a good way to do this?

Or is it all about making the div[ui-view] full height ( not trivial ) and setting the background on this element to simulate the use of the background on the body occupying the full viewport ?

+6
source share
2 answers

So, to summarize, there are two ways to do this. Both require the $state service to be in $rootScope . The elegance of this can be challenged , but I will go for that decision.

  • If the background classes are state dependent , add them to the user data state:

Code example:

 .state({ ..., data: { bodyClass: 'bg1' } }); 

Then, on the body, place the ng class and specify the current state data:

 <body ng-class="$state.current.data.bodyClass"> 
  1. If background classes (besides state) depending on something else (for example, a state or service parameter, ...), use the state resolution mechanism :

Code example:

 .state({ ..., resolve: { bodyClass: function($stateParams) { // do some calculation return ... } } }); 

Then, on the body, put ng-class and specify the resolved class name through $state.$current.locals.globals :

 <body ng-class="$state.$current.locals.globals.bodyClass"> 

In both cases, bodyClass can use anything that suits the ng-class directive.

+2
source

Probably inaccurate, but maybe you could just change the background color of your body directly in the controller?

 stateHelperProvider .state({ name: 'a', url: '/a', templateUrl: 'views/a.html', controller: function ($scope) { document.body.style.background = 'bg1'; } }) .state({ name: 'b', url: '/b', templateUrl: 'views/b.html', controller: function ($scope) { document.body.style.background = 'bg2'; } }); 

Or in this case, just add / remove CSS classes to the body?

Good luck '

0
source

All Articles