What is the method for configuring body attributes in CSS with AngularJS?

Setting the background image of a page using CSS:

body {
    background: url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    text-align: center;
}

Looking to read a property from a scoped variable in the controller:

$scope.image="http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg"

How to set this CSS body attribute within the .html page with AngularJS? jQuery's .css() method is not working. Is there an alternative in AngularJS? http://docs.angularjs.org/guide/dev_guide.templates.css-styling doesn't provide clear instructions.

Here is a fiddle that I tried but it does not work:

http://jsfiddle.net/U3pVM/3015/

Fiddle code:

<body ng-style="getBodyStyle()">
</body>

$scope.getBodyStyle = function () {
    return {background: "url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed;"};
};

Answer №1

In order for your JSFiddle code to work properly, you need both an app and a controller. Currently, your JSFiddle is failing because it lacks a controller and $scope is never defined.

To create a $scope variable named $scope.bodyStyle in a controller, follow this example:

app.controller('MainCtrl', function($scope) {
 $scope.bodyStyle = {background: "url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed"};
});

You should then register the app and the controller in the HTML like so:

<html ng-app="plunker">

<body ng-controller="MainCtrl" ng-style="bodyStyle">
 Demo text
</body>

</html>

I have created a Plunkr to demonstrate the full app functionality, as JSFiddle can be challenging with Angular.

Angular requires more components working together compared to regular JS or JQuery, which can be overwhelming for beginners. I suggest starting with the AngularJS seed app to ease into it.

If you wish to access the background image from a $scope variable, you can implement it like this:

app.controller('MainCtrl', function($scope) {
  $scope.image="http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg";
  $scope.bodyStyle = {background: "url(" + $scope.image + ") no-repeat center center fixed"};
});

Answer №2

Here is an example of how you could achieve this:

<header ng-style="getHeaderStyle()">

Additionally,

$scope.getHeaderStyle = function () {
    return {color: myColor};
};

Answer №3

My approach was to use an API call to retrieve the image URL and store it in the state under resolve:

resolve: {
   'image': ['$http', function($http) {
        return $http.get('/api/image');
    }]
}

The API responds with JSON:

res.json({url: 'someUrl'});

Then, I pass this URL to the controller and simply execute:

angular.element('body').css('background-image', 'url(\'' + image.data.url + '\')');

I find this method clean because it eliminates the need to inject $scope into the controller, which is now discouraged.

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

Issue with Navigation Scrolling Feature on Wordpress

I am in the process of implementing a 'scroll-nav' for my website. To achieve this, I decided to separate the Navigation into two sections and incorporate some jQuery: <nav class="main-nav clearfix"> <?php wp_nav_menu(array('th ...

Error encountered when attempting to create an index in ElasticSearch due to

I am encountering an issue with the elasticsearch npm module while attempting to create an Index, resulting in a TypeError with the following message: Unable to build a path with those params. Supply at least index The code snippet I am using is as follo ...

Sending an AJAX request to a PHP file to retrieve data in JSON format

Greetings everyone, I am currently exploring the world of AJAX for sending information to a JSON file and I'm unsure about the structure of the .php file needed to process it. My experience with .php is quite limited. Can anyone guide me in the right ...

ngTable select all data that has been filtered

I have encountered an issue with selecting only the rows from an ng-table that have been filtered. The current code filters the table rows successfully, but it also selects rows that are not displayed: Controller: let sampleData = [{id: 1, name: 'Jo ...

Having trouble accessing CSS images in JSF

Issue Details : I am currently facing a problem with setting menu background images in my JSF application using CSS properties. The file structure is as follows This is the CSS snippet Style.css #menu { height:35px; width:950px; backgrou ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...

Unusual Characteristics of Synchronous Ajax Requests in JavaScript

First and foremost, I'd like to apologize if my approach seems unconventional. My background is primarily in C development, so I tend to tackle AJAX issues in a way that reflects my experience in C programming. The scenario at hand involves a script ...

I am interested in creating a text box that has the ability to gather user input and connect it to a search

I have been attempting to develop a text box that can collect answers and link them with the search URL. However, I am encountering issues where even though I can input text into the textbox, it is not being recognized by the script. The error message sh ...

What is the best way to position the publication date of an article at the bottom of the

I am looking to have the article publishing date (1/9/2016) positioned at the bottom inside the container. Right now, the date appears just below the text, but I want it to be aligned at the bottom of the container. The website in question is watchathletic ...

Deactivate a span in real-time using ng-model

I found a helpful guide on creating a custom editable <span> using ngModelController here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#example Now, I am looking to implement a feature that allows me to dynamically disable editin ...

Is the memory efficiency of Object.keys().forEach() in JavaScript lower compared to a basic for...in loop?

Picture a scenario where you have an extremely large JS object filled with millions of key/value pairs, and your task is to loop through each of them. Check out this jsPerf example that demonstrates the different techniques for accomplishing this, highlig ...

Assets directory containing Dropwizard service directory

Currently, I have set up my Dropwizard/AngularJS website to serve assets from an AssetsBundle located in the root directory: public void initialize(Bootstrap<WebsiteConfiguration> bootstrap) { bootstrap.addBundle(new AssetsBundle("/assets/", "/" ...

Error: The function $q is undefined in angulargrid.js

Currently, I am utilizing this Angular library to display images in a Pinterest-like manner. The library includes the following code snippet: function ngCheckAnim() { var leavingElm = domToAry(listElms).filter(function(elm) { return single(elm ...

Problem with validation in jQuery not being compatible with Kendo Button (sample code provided in jsfiddle)

It took me some time to figure out that the reason jquery-validate wasn't functioning in my Kendo Mobile application was because my submit button was a Kendo Button. Check out this jsfiddle for illustration: DEMO <div id="phoneApp" style="displa ...

Insert a section of background within the div

Does anyone know how to create a div with a partial background like the example shown here? I attempted to add white margin, but I'm struggling to get it right. ...

changing the vertical position of an element using JavaScript

I'm currently working on a project where I have a canvas that animates upwards when a button is clicked. However, I'm facing an issue with making it go back down after the animation completes. It seems to be getting stuck and not returning to its ...

Tips for customizing CSS hover effects using HTML and jQuery scripts

Just a heads up before I ask my question - the code I'm about to share is sourced from this video on YouTube, so all credit goes to the creator. JS $(".product-colors span").click(function(){ $(".product-colors span"). ...

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

Utilizing JavaScript for validation on an ASPX page within Visual Studio

After entering an email ID in a textbox, the email validation process is initiated. However, it seems that there is an issue where the entire function may not be executed properly. <head runat="server"> <title></title> ...

Is it possible to generate an image from HTML using PHP?

Can anyone suggest a way to generate an image from pure HTML using PHP, possibly utilizing the GD library or other similar tools? I am looking to display icons from external sites and considering if creating an image would help improve load times. If not ...