Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change body tag class in Angular 1

My problem is I have multiple pages that require a different body class for each page.

So without using $rootScope how can I change this in the DOM depending on which page is being displayed?

<body class="class-that-needs-changing">

1 Answers

Let's make use of a directive like this:

.directive('bodyClasses', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var classes;

            scope.$watch(function(scope) {
                return scope.$eval(attrs.bodyClasses);
            }, function(value) {
                classes = value;
                angular.element(document.body).addClass(value);
            });

            // Remove body class when scope or directive destroyed.
            scope.$on('$destroy', function() {
                angular.element(document.body).removeClass(classes);
            });
        }
    };
});

Now, use this directive in your separate HTML pages like this:

<!-- remember, use single quote for string since we are evaluating it -->
<div body-classes="'new-class another-class'"></div>

or

<span body-classes="'foo' {{someScopeVariable}}"></div>

As a particular page or view will load, those classes will be added to the body tag. In this way, you can keep your class separate in each individual page and your main body tag will not clutter.

like image 109
Shashank Agrawal Avatar answered Feb 03 '26 01:02

Shashank Agrawal