AngularJS Changing <body> class using global variable AngularJS Changing <body> class using global variable angularjs angularjs

AngularJS Changing <body> class using global variable


You can create global variables in two way

Using $rootScope you can do something like in your LoginController controller

angular.module('myApp').controller('LoginController', function($scope, $location, $window, $rootScope) {   $scope.user = {};   $rootScope.bodylayout = 'login-layout';   //others code }

Using service

angular.module('myApp').factory("myService", function(){      return {        sharedObject: { data: 'login-layout' }      }; });

Use this service in your controller

angular.module('myApp').controller('LoginController', function($scope, $location, $window, myService) {       $scope.user = {};       $rootScope.bodylayout = myService.sharedObject.data; // get data from service       //others code     }

Where your HTML looks like

<body class="{{bodylayout}}">

Note in this case you need to set bodylayout in each controller otherwise it use the old value


Try using the $rootScope:

$rootScope.bodyClass = 'login-layout';<body class="{{$root.bodyClass}}">

You could handle this in the individual controllers, or perhaps in your app.js by listening for routeChangeSuccess:

$rootScope.$on('$routeChangeSuccess', function (event, currentRoute) {    switch(currentRoute.templateUrl) {        case 'login.html':        case 'register.html':        case 'forgotpassword.html':            $rootScope.bodyClass = 'login-layout';            break;        default:            $rootScope.bodyClass = '';            break;    }});


You could create a <body> directive that has add and remove class events that can be triggered throughout your app.

angular.module('myApp').directive('body', [function(){  return {    restrict: 'E',    link: function(scope, element, attrs) {      scope.$on('body:class:add', function(e, name){        element.addClass(name);      };      scope.$on('body:class:remove', function(e, name){        element.removeClass(name);      };      return;    }  };}]);

In your app.js config block you can set the <body> class to whatever you want with $emit

## Add class$rootScope.$emit('body:class:add', 'login-layout')## Remove class$rootScope.$emit('body:class:remove', 'login-layout')

it just simply uses the angular jqLite addClass() and removeClass() and also doesn't require you to tap into $element by using the directive link function which already has dom access to the element.

Even without $rootScope you can call it within your controllers with $scope.$emit('body:class:add', name).