Altering the background image of the body in Angular by utilizing $rootScope

I need to customize the background image based on specific routes in my application. However, I am facing an issue with the rootScope not updating the value as expected. I have set the value to true in the controller for the route that requires a different background image. Can anyone point out what mistake I might be making here? Is it not possible to utilize $rootScope in routes to modify the body's class?

HTML:

<body ng-app="ciscoImaDashboardApp" dynamicBodyBg ng-controller="navCtrl" >

JS:

.directive('dynamicBodyBg', function($rootScope, $route){
    return {
        restrict: 'A',
        link: function($scope, el){
          $rootScope.$on('$routeChangeSuccess',
            function() {
              if ($route.current.locals.needToChange()){
                el.css({background: url('images/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c0e0d0f070b1e03190208410e0d1e072c5e1442061c0b">[email protected]</a>')});
              }
              else { 
                el.css({background: url('images/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c7e7d7f777b6e736972785c2e6432766c7b">[email protected]</a>')});
              }
            }
          );
        }
    }

});

Routes:

angular.module('ciscoImaDashboardApp', ['ngRoute'])
  .config(function ($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'views/welcome.html',
    controller: 'welcomeCtrl'
  })
  .when('/overall-results', {
    templateUrl: 'views/overall.html',
    controller: 'overallCtrl'
  })
  .when('/swim-lane-results', {
    templateUrl: 'views/swim-lane.html',
    controller: 'swimlaneCtrl'
  })
  .when('/key-exemplifiers', {
    templateUrl: 'views/key-exemplifiers.html',
    controller: 'petalCtrl'
  })
  .when('/key-exemplifiers/:exemplifier', {
    templateUrl: 'views/single-exemplifier.html',
    controller: 'keyCtrl',
    resolve: {
      needToChange: function(){
        return true; //or false
      }
    }
  })
  .otherwise({
    redirectTo: '/'
  });

});

Answer №1

If you are utilizing ng-route in your project, consider the following steps:

To begin, include this directive within your body tag.

app.directive('dynamicBodyBg', function($rootScope, $route){
  return {
    link: function($scope, el){
      $rootScope.$on('$routeChangeSuccess',
        function() {
          // Check if the router has changed and update the background accordingly
          // Implement the logic here
          if ($route.current.locals.needToChange){
            el.css({background: url('//desired-background-url'}); 
          }
          else { 
            el.css({background: url('//default-background-url'}); 
          }
        }
      );
    }
  }
});

In your $routeProvider, define the route settings as follows:

  $routeProvider
  .when('/', {
    templateUrl: 'views/welcome.html',
    controller: 'welcomeCtrl',
    resolve: {
      needToChange: function(){
        return true; //or false
      }
    }
  })

Additionally, I recommend transitioning to ui-router for a more straightforward and maintainable solution.

Answer №2

To tackle this issue, I implemented a root-level scope and applied the necessary changes across all views.

$rootScope.backgroundImg = "url('../images/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d6d6f676b64687e34663c7a3e2433">[email protected]</a>')";

Subsequently, I incorporated it into my view as shown below:

<body ng-app="ciscoImaDashboardApp" ng-controller="navCtrl" ng-style="
{'background-image': backgroundImg}" >

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 serializing a form in jQuery to be used in the URL hash without actually submitting the form

Looking to develop a unique way to create a string representation of specific html forms that can be stored in the hash portion of a URL. I had hoped there was a method available through jQuery, but 'serialize()' seems promising. However, all th ...

At what juncture is the TypeScript compiler commonly used to generate JavaScript code?

Is typescript primarily used as a pre-code deployment tool or run-time tool in its typical applications? If it's a run-time tool, is the compiling done on the client side (which seems unlikely because of the need to send down the compiler) or on the s ...

When using NextJS, the dynamically generated HTML elements do not get affected by CSS repaint

Recently, I encountered an issue while working on a Next.js project involving the addition of an external script that uses vanilla JavaScript to dynamically create nodes. Despite importing global CSS at the top of my _app.js file, I noticed that the styles ...

Dragging is disrupted by text overlays in Three.js

After following the recommendations on GitHub (https://github.com/mrdoob/three.js/issues/1321) and also here on StackOverflow (Dynamically create 2D text in three.js), I decided to overlay text using HTML divs. However, a problem arises when the user rota ...

Requesting data download via AJAX for a CSV file

I have a unique feature on my website where users can customize and download a summary page based on specific elements they select to include in the final CSV file. To streamline the process, I want to display the summary page to the user and initiate the ...

Updating class on elements in arrays

There are multiple elements, each with a unique ID "xxx_view_ch_&&&" within an outer div with the ID "xxx_view_&&&". The goal is to change the class of the element with the ID "xxx_view_ch_&&&" when the user clicks on the entire element ("xxx_view_&&&"). ...

Obtain the file path and store it in a variable right after using fs.writefile

Can anyone assist me in obtaining the file path of the created file in the following code snippet? I am passing a barcodeSourceNumber as a parameter and expecting the file path as the return value. pathToFile = generateBarcodeImage('123456789'); ...

Redirect in Angular when there are no parameters in the URL

Whenever a user forgets their password, an email containing a URL is sent to their account. I am looking to create a page for resetting passwords that will only load if the URL has a specific parameter. My framework of choice is Angular. For instance: If ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

Angular Routing for a specific page path

I am currently in the process of working on a project using the MEAN stack and I have encountered an issue with getting a specific template to display on a particular URL. Currently, when users visit www.myurl/catalog, it loads the catalog.html template, ...

Using javascript to save the contents of a textbox as cookies, then displaying the result

I am a beginner in the world of JavaScript and I am looking for an easy solution. Can someone please guide me on how to store the values entered in two text boxes on one HTML page, and then display them on another HTML page? ...

In Javascript, use the replace() function to target and replace text that is not contained

Seeking help with highlighting search strings in an autocomplete form. In my current approach, I aim to encapsulate the search term within specific tags for emphasis. However, complications arise when the pattern resides within HTML tags. var searchPatter ...

The Issue with My Ajax Request Not Working When Clicking an Icon

When I click on an icon, I want to trigger an AJAX call. Script.js $('.user-status').click(function() { var userId = this.id; var userStatus = $(this).attr('data-status'); alert('clicked'); $.ajax({ t ...

In angular, concealing the pagination bar can be achieved when the quantity of pages is lower than the items per page count. Let's delve into

I am facing an issue where I need to hide the pagination bar if the number of pages being rendered is less than the items per page. I attempted to use ng-show but it was not successful. <tr ng-repeat="row in allItems"> ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...

Scripts in iframes within webviews are not preloading and executing properly

When using the <webview> tag in the renderer process within the <body> of a web page, the following code is used: <webview src="http://somewebpage.com" preload="somescript.js"> The script somescript.js will be execute ...

The video rendered with fluent-ffmpeg appears to have an elongated image

I am working on combining an mp3 audio file with a jpg image file to create a new mp4 video. Although I have a functional fluent-ffmpeg command that accomplishes this task, there is an issue where the image gets stretched in the final output video, especia ...

Tips on updating the text of markers in ng-map from 'A' to 'B' and vice versa

Looking to customize ng-map markup to display "start" and "end" instead of "A" and "B." Referenced this resource, but encountered issues displaying both "start" and "A" in the markup. Noticing a discrepancy in the distance between the source and destinat ...

Issue occurred while executing the fs.rename() function in a loop in Node.js

I'm currently working on a project that involves organizing uploaded files into folders based on their request ID. I am using express-request-id to retrieve this ID. The issue I am facing is that whenever there are multiple files to be moved, the pro ...

Issue with iframes crossing domains

Imagine I have a website called example.com which embeds an iframe from domain iframe.net. My goal is to extract the content of the iframe and add a parameter to display a personalized message, such as "Hi [username]". The issue I'm facing is that I ...