Implementing a custom body class in AngularJS when utilizing partials

Looking for some help with AngularJS.

I have an index.html file, along with controllers and partials.

The <body> tag is located in the index.html. I am trying to set the class for the body using my controller.

After adding a value to $scope.body_class and referencing it in my index.html like this:

<!doctype html>
<html lang="en" ng-app="myGreatApp">
...
<body ng-class="{body_class}"> {{body_class}} Hi!

Unfortunately, body_class doesn't return any value.

How can I successfully retrieve a value from body_class?

Answer №1

When using directives in AngularJS, it is important to define the controller on the element or a parent element in order for them to interact properly. Alternatively, you can inject $rootScope and use it instead. The ng-class directive accepts a hash like this:

<body ng-controller="YourController" ng-class="{body_class: <expression>}"> {{body_class}} Hi!

If <expression> evaluates to true, the element will receive a html class corresponding 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!

Alternatively, if you do not want to declare the class name in the markup, you can directly bind it using ng-class like this:

<body ng-controller="YourController" ng-class="body_class"> {{body_class}} Hi!

For more information, refer to the ng-class documentation

Answer №2

Give this a try:

Controller

function DisplayCtrl($scope){
$scope.MyText = 'Welcome'
}

HTML

<body data-ng-app="" data-ng-controller='DisplayCtrl'>
<div data-ng-class="MyText">Welcome to the world
</div>
</body>

Check out this JsFiddle example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for enabling mouse functionality while utilizing PointerLockControls

I'm currently working on a 3D art gallery using Three.js and PointerLockControls for navigation. My goal is to have the artwork on the gallery walls clickable, triggering a pop-up window with additional information. However, it seems that PointerLock ...

`In AngularJS, the same URL ('/') can display different templates depending on the user's login status.`

What is the most effective way to configure routing and templates in AngularJS to display a distinct front end and login area for visitors, while presenting a dashboard to logged-in users all on the same base URL ('/')? These two pages have comp ...

problem arising from the origin preventing me from utilizing localStorage in conjunction with JSDOM

Currently, I am facing an issue while trying to load a webpage in a node environment using JSDOM. The webpage relies on localStorage for its functionality. I have attempted to load the webpage by utilizing JSDOM's URL configuration option and accessi ...

I'm confused, I installed the module but it's still showing an error message saying it can

I've been working on coding a discord music bot, and here is the code I have so far: const config = require('config.json') const Discord = require('discord.js'); const ffmpeg = require('ffmpeg-extra') const client = new ...

Having trouble with `$resource` in AngularJs but everything seems to be working fine with `$http`. Wondering how to transfer the parameters used in `$http`

Having some trouble posting image information to the backend. I attempted using $resource, but it didn't work. However, when I switched to using $http, it seemed to work fine. The issue is that I need to apply additional parameters to $http, and I&apo ...

The Final Div Fluttering in the Midst of a jQuery Hover Effect

Check out my code snippet here: http://jsfiddle.net/ZspZT/ The issue I'm facing is that the fourth div block in my example is flickering quite noticeably, especially when hovering over it. The problem also occurs occasionally with the other divs. Ap ...

Is it possible to host multiple React applications on a single port? Currently experiencing issues with running both an Admin panel and the Front side in production mode on the same Node.js API server

Is it possible to host multiple React applications on the same port? I am experiencing issues with running both an Admin panel and a Front side React app in production mode on the same Node.js API server. ...

Guide on transferring data from an API using mapped React hooks

I am working with react hooks and attempting to pass a value to the delete function and execute the put function <Fab aria-label="delete" className={classes.fab} value={vacation.id} ...

Unable to locate a declaration file for the module "../constants/links" in src/constants/links.js, as it implicitly defaults to type 'any'

Within my VueJS application, I have brought in some constant variables. <script lang="ts"> import { Component, Prop, Vue } from 'vue-property-decorator' import { MOON_HOLDINGS_LINK, TWITTER_LINK } from '../constants/links' @Comp ...

What makes using the `@input` decorator more advantageous compared to the usage of `inputs:[]`

In defining an input on a component, there are two available methods: @Component({ inputs: ['displayEntriesCount'], ... }) export class MyTable implements OnInit { displayEntriesCount: number; Alternatively, it can be done like this ...

What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like thi ...

Switching from "Straight Quotes" to "Curly Quotes"

Looking for a solution to convert regular straight quotes into curly quotes in a Javascript-based rules engine application. Rather than just using a simple string.replace for ["], I need a method that will insert the correct curly quote depending on its po ...

Angular with Flask: Form submitted via POST method is returning empty

When I send data through an AngularJS POST request: $http.post('/process', { 'uid': uid, 'action': action }).success(function(response) { console.log(response); }); I attempt to retrieve the passed values in Flask @app. ...

Why would someone opt to utilize process.env.PORT in their code?

Setting the environment variable PORT to a specific value, such as set PORT=5000, provides explicit instructions on which port the program should use. How does this method differ from simply instructing it to use port 3000? ...

I'm experiencing very slow page load times in dev mode with Next.js (30s+). What could be the reason behind this sluggishness?

QUESTION: Encountering a similar issue (but with different files): https://github.com/vercel/next.js/discussions/17977 I've already tried all the suggestions provided in that discussion. This is what the page load process looks like in development ...

"Exploring the process of looping through a JSON object following an asynchronous retrieval of JSON data using

I am facing an issue while trying to iterate through a JSON object in jQuery after fetching it asynchronously. I have a function called 'listFiles' that uses async to successfully retrieve a file list from a directory (dir) by calling an API endp ...

Double your audio experience with Webaudio by playing the sound twice

While working on WebAudio experimentation, I encountered an issue with loading a sound using the JavaScript code below. function playAudio(){ var audio = document.getElementById('music'); var audioContext = new webkitAudioContext(); ...

What are some ways to optimize the efficiency of handling a sizable JSON object in React Native?

I am currently developing an application using React Native and have encountered significant slowdowns during transitions when loading more data. I am exploring alternative app structuring methods to prevent these performance issues, especially as the JSON ...

Is there a way to retrieve the `this.$route` data while using vue-apollo?

Currently working on building a GraphQL query with vue-apollo and graphql-tag. When I manually set the ID, everything runs smoothly. However, I'm aiming to dynamically pass the current route's ID as a variable to Vue Apollo. Successful Implemen ...

Trigger event listener of AngularJS directive on click and send information to it

During my exploration of AngularJS directives, I encountered a task that required me to activate the directive's listener upon clicking a button and passing data from the controller to it. Sample Directive app.directive('graphVisualization&apos ...