Skip to content Skip to sidebar Skip to footer

Changing Body Background Color With Angularjs

I want to be able to change the background color of depending on what the current path is. I tried doing it by checking $location.path() whenever the path was changed

Solution 1:

To decouple such a dynamic change in style, data, content and etc., it is often practical to create another angular module that contains an interface(Custom Provider) that can give you access to these changes before and after the configuration level. Here is a plunker to provide a view of what I'll be discussing below.

For this answer, I have created a small module(route-data.js) with a provider, RouteData, which exposes two function configurations:

applyConfig() - assigns settings to be accessed in the RouteData service. hookToRootScope() - hooks the RouteData service in the $rootScope hence making it available to all child scopes to be created and the entire application.

The RouteData provider has a RouteData() service that provides access to methods which sets and gets RouteData settings that will be provided in the $routeProvider configuration.

(If you're not familiar with providers and services, read more about it here)

(If you're not familiar with the config() and run() methods, you can read more in here)

route-data.js

angular.module('RouteData', []).

provider('RouteData', function () {
  var settings = {};
  var hookToRootScope = false;

  this.applyConfig = function(newSettings) {
    settings = newSettings;
  };

  this.hookToRootScope = function(enableRootScopeHook) {
    hookToRootScope = enableRootScopeHook;
  };

  functionRouteData() {

    this.set = function(index, value) {
      settings[index] = value;
    };

    this.get = function(index) {
      if(settings.hasOwnProperty(index)) {
        return settings[index];
      } else {
        console.log('RouteData: Attempt to access a propery that has not been set');
      }
    };

    this.isHookedToRootSope = function() {
      return hookToRootScope;
    };
  }

  this.$get = function() {
      returnnewRouteData();
  };
}).

run(['$location', '$rootScope', 'RouteData', function($location, $rootScope, RouteData) {
  if(RouteData.isHookedToRootSope()) {
    $rootScope.RouteData = RouteData;
  }

  $rootScope.$on('$routeChangeStart', function(event, current, previous) {
    var route = current.$$route;
    if(typeof(route) !== 'undefined' && typeof(route['RouteData']) !== 'undefined') {
      var data = route['RouteData'];
      for(var index in data)
        RouteData.set(index, data[index]);
    } 
  });
}]);

The script below shows how to use the RouteData Module above via injecting the RouteDataProvider in the configuration level and apply default configurations such as the bodyStyle via RouteDataProvider.applyConfig(), you may also add more settings before the application is fully running. Hook it up in the $rootScope by setting RouteDataProvider.hookToRootScope() to true. Lastly, appending data, RouteData e.g.

RouteData: {
      bodyStyle: {
        'background-color':'green'
      }
    }

to be sent in by the $routeProvider and processed by the run() method defined in the RouteData module which initializes the settings for the RouteData services to be accessed in the application.

script.js

angular.module('app', ['ngRoute', 'RouteData']).

config(['$routeProvider', 'RouteDataProvider', function($routeProvider, RouteDataProvider) {
  RouteDataProvider.applyConfig({
    bodyStyle: {
      'background-color': 'white'
    }
  });

  RouteDataProvider.hookToRootScope(true);

  $routeProvider.when('/landing', {
    RouteData: {
      bodyStyle: {
        'background-color': 'green'
      }
    },
    templateUrl: 'landing.html',
    controller: 'LandingController'  
  }).when('/login', {
    RouteData: {
     bodyStyle: {
         'background-color': 'gray',
         padding: '10px',
         border: '5px solid black',
         'border-radius': '1px solid black'
     }
    },
    templateUrl: 'login.html',
    controller: 'LoginController'
  }).otherwise({
    redirectTo: '/landing'
  });

}]).

controller('LoginController', ['$scope', function($scope) {

}]).

controller('LandingController', ['$scope', function($scope) {

}]);

So the final piece of code to be added in your index page or any other page would be something like this.

A portion of index.html

<bodyng-style="RouteData.get('bodyStyle')"><ahref="#/landing">Landing</a> | 
    <ahref="#/login">Login</a><divng-view></div></body>

Solution 2:

One way to style the body is to add ng-view as a body attribute, then use ng-class or ng-style (I did not use any other option to date).

For example:

<!doctype html><htmlng-app="my-app"><head><title>My Site</title><scriptsrc="angular/angular.js"></script></head><bodyng-class="{login:loginBody}"ng-view><scriptsrc="my-app.js"></script></body></html>

In this example, the login class is applied to the body only when loginBody is a true value in the current scope, set in a login controller.

This is much less flexible than the approach offered by @ryeballar. It may just be enough in some cases.

Solution 3:

I noticed that when I navigate to another page without page reload background color still remains, so I am doing this (I am using angular ui-router):

In config:

$stateProvider.state('app.login',{
            url: '/login',
            onExit: function($rootScope){
                $rootScope.bodyClass = 'body-one';
            },
           templateUrl: 'ng/templates/auth/login-page-one.html',
            controller: function($rootScope){
                $rootScope.bodyClass = 'body-two';
            }
        })

        .state('app.signup',{
            url: '/signup',
            onExit: function($rootScope){
                $rootScope.bodyClass = 'body-one';
            },
            templateUrl: 'ng/templates/auth/signup-page-one.html',
            controller: function($rootScope){
                $rootScope.bodyClass = 'body-two';
            }
        });

In the Template

<body class="{{bodyClass ? bodyClass : 'body-one'}}">

In CSS:

.body-one{
    margin-top: 50px;
    background: #f0f4fb;
}

.body-two{
    margin: 0;
    padding: 0;
    background: #2e9fff;
}

Post a Comment for "Changing Body Background Color With Angularjs"