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">
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With