Setting body class while using partials in AngularJS
-
20-12-2019 - |
Question
Another AngularJS newbie question.
I've got an index.html, controllers, and partials.
My <body>
tag is in the index.html ... and I want to set the class for the body in my controller.
So I tried sticking a value in $scope.body_class
and then referencing that variable in my index.html, like this:
<!doctype html>
<html lang="en" ng-app="myGreatApp">
...
<body ng-class="{body_class}"> {{body_class}} Hi!
But body_class
doesn't return a value.
How do I get body_class
to return a value?
Solution
For starters, the controller has to be defined on the element or any parent element for it to be able to interact with the directives (or you will have to inject the $rootScope and use it instead) and, the ng-class directive accepts a hash, so
<body ng-controller="YourController" ng-class="{body_class: <expression>}"> {{body_class}} Hi!
and if <expression>
is thruthy, it will get a html class
that corresponds to the key in the hash.
<body ng-controller="YourController" ng-class="{body_class: true}" class="body_class"> whatever value $scope.body_class has Hi!
If you dont need to declare the class name in the markup, the ng-class directive also accepts a direct binding, so you can instead:
<body ng-controller="YourController" ng-class="body_class"> {{body_class}} Hi!
OTHER TIPS
Try this:
Controller
function SampleCtrl($scope){
$scope.MyClass = 'Hello'
}
HTML
<body data-ng-app="" data-ng-controller='SampleCtrl'>
<div data-ng-class="MyClass">Hello World
</div>
</body>