Wayne Li Wayne Li - 20 days ago 8
AngularJS Question

Set different body background for different pages when using AngularJS template and ui-router

I have two pages and I'm using

ui.router
to jump around different pages. One is a login page and after login, the page will jump to a home page.I want to set the a body
background-color
for login page but set another body
background-color
for another. If I just set color for the template
div
, the color won't be applied to the body background, but if set color directly to the background, then two pages have the same color. What can I do?

HTML:

<body>
<div ui-view="header"></div>
<div ui-view="content"></div>
<!-- build:js scripts/main.js -->
</body>


JS:

angular.module('app',[....]).config(function ($stateProvider,$urlRouterProvider) {
$stateProvider
.state('login',{
url:'/',
views:{
'content':{
templateUrl:"views/login.html",
controller:"LoginController"
}
}
})
.state('home',{
url:'/home',
views:{
'header':{
templateUrl : "views/header.html",
controller: 'HeaderController'
},
'content':{
templateUrl: "views/homePage.html",
controller : 'HomeController'
}
}
})

Answer

In a global controller (which is applied to either <html> or <body> tag), register an event:

myApp.controller('GlobalCtrl', function($scope) {
    // Event listener for state change.
    $scope.$on('$stateChangeStart', function(event, toState, toParams) {
        $scope.bodyClass = toState.name + '-page';
    });
});

Now, in your HTML:

<body class="{{bodyClass}} foo bar" ng-controller="GlobalCtrl">
   <!-- your content -->
</body>

Now, in your CSS:

body.login-page {
    background: green;
}

body.home-page {
    background: red;
}
Comments