Using AngularJS ng-style to set dynamic background images for different variables

Excuse me if this is a basic question. I am working on designing a login page with a background image, while the other pages don't have this background. I tried using ng-style but couldn't get the style to update when navigating between pages. In my index.html:

<body ng-app="myApp" ng-style="bodyStyle" ng-controller="bodyController">
  //content
</body

bodycontroller:

var image="http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg";
if ($location.path() === '/login') {
  $scope.bodyStyle = {background: "url(" + image + ") no-repeat center center fixed"};
} else{
  $scope.bodyStyle={background: ""}
} 

This approach doesn't work because the function is only called once. I also attempted using rootScope, however, I couldn't use rootScope properties in ng-style as advised by others. How can I create a dynamic background without using a controller on the body tag?

update

The issue I'm facing is that the background image does not update when changing paths. The image is set in bodycontroller and remains unchanged while logging in and switching paths.

One suggestion is to create a service. I've used services before for getters and setters, so I assume I can create one that interacts with a controller. It would look something like this:

<body ng-app="myApp" ng-style="bodyStyle" ng-controller="bodyController">
   //content
</body

bodycontroller

var image=??;
$scope.bodyStyle = {background: "url(" + image + ") no-repeat center

some service

 .service('backgroundService', function (image) {
    var backgroundImage = image
    // somehow set bodycontroller's image?
 });

and then somehow call the service when the route is changed? I haven't figured out how to inject services into my router config, which I believe is necessary for this setup.

Answer №1

After some helpful guidance, I discovered a simple method to achieve this task.

To implement this in app.js, include the following code:

.run(function ($rootScope, $location) {
  $rootScope.$on( "$routeChangeStart", function(event, next, current) {
    $rootScope.bodyClass = $location.path().replace('/', '') + '-page';
  });
});

Update the index to:

<body ng-app="myApp" ng-class="bodyClass">

Finally, apply the CSS:

.login-page {
  background: url("someImage") no-repeat center center fixed;
}

Answer №2

In my opinion, a more efficient approach would be to toggle an ng-class based on the location. You could achieve this by using the following code:

if ($location.path() === '/login') {
$scope.isLogin = true;
} else{
$scope.isLogin = false;
}

Then in the html file:

<body ng-app="myApp" ng-class="{'customBgClass' : isLogin }" ng-controller="bodyController">

You can then define the styles for the custom background class like so:

.customBgClass {
   background: url("http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg") no-repeat center center fixed;
 }

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

Can you help me modify the navbar color in Bootstrap 4 based on the screen width?

For example, if I use the navbar-dark and bg-dark classes in a nav tag, I want to switch them to navbar-light and bg-light when the screen width is changed to approximately 600px (using Bootstrap 4). ...

Tips for automatically expanding all nodes with children when the page loads in the Wix Angular tree control

Is there a way to automatically expand all nodes with children when the page loads in an Angular tree control? The tree control is full of useful features, but this specific functionality seems to be missing. It does have a property for expanded nodes. Do ...

Adsense ad unit is not responsive and fails to display properly at dimensions of 320x50 px

I have a unique banner ad that I want to display as the footer on my responsive website. Using media queries recommended in the advertising documentation, I am adjusting the size based on different screen widths. Check out the CSS code below: <style&g ...

Creating a dropdown menu that seamlessly populates elements without any empty spaces

My team at the company is using a menu created by another developer. I recently added a dropdown selection to the first item on the menu, but I've run into an issue where the dropdown box does not fully fill the item, and I can't seem to fix it. ...

The GitHub Pages website is not displaying exactly like it does when running locally with a live server

Currently in the process of creating a compact website where users can input an anagram and receive all potential words that can be formed from it. Additionally, upon receiving these words, there is an option to click on one for its definitions. The site ...

Scaling boxes responsively according to screen size utilizing Bootstrap

Creating a portfolio website with a carousel section to display completed projects in a 2x2 grid layout, transitioning to a 1x4 on smaller screens is proving to be quite challenging. After trying various methods from Bootstrap documentation and YouTube tut ...

Separate the two divs with some added spacing

I am facing a challenge in creating a navbar with two regions split by white space. I attempted to use float:right and justify-content: space-between, but it doesn't seem to work as expected. My goal is to have site-header-right on the right side and ...

Intellij2016 is issuing warnings for the sass use of the :host selector in Angular2 code

One interesting feature of Angular 2 is the special selector it uses to reference its own component: :host display: block height: 100% !important width: 100% text-align: center position: relative However, Intellij does not provide a way to supp ...

Conceal the slider image without removing it

Is there a way to hide the slider background image on mobile screens? @media screen and (max-width: 800px){ .home #mainSliderWrapper { background-image: none; } .stlye { background-image: none; } .img--holder { background-image:none; } } I tr ...

What is the best way to position an image in the center over a video using HTML and CSS?

I am currently developing a website with a background video and I want to overlay a company logo on top of it while keeping it centered. My coding language of choice for this project is using HTML and CSS. Here's the HTML code snippet I have for this ...

What is the process for implementing a third-party component in my web application?

After some experimentation, I've discovered that it's necessary to include the link to the css files in the header and then mention the link to the js files before the closing tag. However, I encountered difficulties when trying to use a compone ...

How to transform a hyperlink into a clickable element within an absolutely positioned container

I'm currently working on a photo gallery project and using magnific popup to create it. However, I ran into an issue with the hover event on the images that displays an icon when it's hovered over, indicating that it can be clicked to view more. ...

The ng-repeat radio buttons are incorrectly selecting the wrong radio button

On my webpage, I am using ng-repeat to display a list of radio buttons. Strangely, when the page first loads and I click on the last radio button, the one next to it gets selected instead. This odd behavior only occurs the first time; if I click on the ...

What is the reasoning behind beginning the transition with autofocus enabled?

After creating a contact form with autofocus="autofocus", a strange behavior was noticed. It seems that when the form has autofocus, the transition effect on the navigation bar is triggered in Firefox only. Is this an error on my end or just a bug specific ...

Achieve seamless alignment of radio group labels alongside radio buttons through the use of only CSS

After using a table to display radio buttons with labels in the past, I am now attempting to achieve the same result using only CSS. Is there a CSS technique that will allow me to position the label text neatly on top of the corresponding radio button? He ...

Is it important to position elements based solely on the parent container?

My frustration with element positioning persists: <div id="container"> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> </div> #div1 { right:0; // I want its right border to be 0px from th ...

Incorporate a CSS framework into the Angular vendor bundle

My current situation : The website is built with Angular 4 Started using Angular Starter Kit Utilizing Semantic UI as the CSS framework The challenge I'm facing : Integration of Semantic UI into webpack is not having any impact. Steps I've ...

What is the best way to display the status of lengthy tasks being processed on the server using AngularJS in the client side

On the backend, I have a web API that is responsible for approving multiple invoices at once. By setting a flag called approveAll=true, the API operates asynchronously by looping through each invoice and updating its status to APPROVED. Meanwhile, on the ...

Ways to Randomly Flip Divs

I have developed an application where all divs flip vertically on hover. I am looking for a way to make the flipping random without requiring a hover. Any ideas on how to achieve this? .vertical.flip-container { position: relative; float: left; ma ...

Issue with the successful execution of connection event handler in NodeJS and Socket.io?

When I look at my code in files named server.js and index.html, I notice that the io.on('connection') part is not executing the console.log method in its callback when I visit my server in the web browser. Take a look at the code snippets below ...