Angular.js: Applying a style to elements beyond the current scope based on the selected route

I'm looking to dynamically add classes outside of the current scope. Specifically, I need to add classes to the header, main, and footer elements as shown below:

<header class="{{pageClass}}"></header>
<main class="{{pageClass}}" ng-view></main>
<footer class="{{pageClass}}"></footer>

Below is my routing configuration along with the corresponding controllers:

app.config(function($routeProvider) {

    $routeProvider
    .when('/chapter/:title', {
        templateUrl: 'article.html',
        controller: 'article'
    })
    .when('/search', {
        templateUrl: 'search.html',
        controller: 'search'
    })   
    .otherwise({
        redirectTo: '/search'
    });

});

app.controller('article', function($scope) {
    $scope.pageClass = 'normal';
});

app.controller('search', function($scope) {
    $scope.pageClass = 'small';
});

I want to assign the class 'normal' when a user opens an article and 'small' when they visit the search page. This way, each of the three tags (header, main, and footer) will always have a specific class based on the routing used.

Overall, the goal is to provide different styling based on the routing path. I hope this explanation clarifies my objective.

Answer №1

To ensure that the class is accessible, assign it to a parent scope or to $rootScope if no other parent scope is present.

The scope of ng-view is limited to the tag and its descendants only.

Update your controllers as shown below:

app.controller('article', function( $rootScope ) {
    $rootScope.pageClass = 'normal';
});

app.controller('search', function( $rootScope ) {
     $rootScope.pageClass = 'small';
});

Answer №2

Incorporating a parent controller for the body tag involves setting up an object $scope.parent = {}; that contains the className.

Important to Note

The use of $scope.parent = {}; allows the child controller to directly access the className using $scope.parent.className, utilizing Javascript prototypal inheritance.

HTML Markup

<body ng-controller="parent">
  <header ng-class="parent.className"></header>
  <main ng-class="parent.className" ng-view></main>
  <footer ng-class="parent.className"></footer>
</body>

AngularJS Code

app.controller('parent', function($scope) {
    $scope.parent = {};
});

app.controller('search', function($scope) {
    $scope.parent.pageClass = 'small';
});

app.controller('article', function($scope,) {
    $scope.parent.pageClass = 'normal';
});

Check out this Plunkr example

Answer №3

In my application, this is the approach I take:

  1. I create a main Controller that encapsulates all components.

    <html ng-controller="AppCtrl">
    <---- code --->
    <body onload="onLoad()" class="{{ viewClass }}">
        <div id="page" class="scale-fade-fast" ng-view></div>
    <---- code --->
    
  2. Main module's route configuration:

    MainApp.config(['$routeProvider', function($routeProvider){
           $routeProvider
               .when('/path', {
                  viewClass: 'myPageClass',
                  templateUrl: 'path/to/tpl',
                  controller: 'AnotherCtrl'
               })
    <---- code --->
    
  3. Listening for route changes in the main controller:

    MainApp.controller('AppCtrl',['$scope', function($scope){
        $scope.viewClass = 'defaultPageClass';
        $scope.$on('$routeChangeSuccess', function(evt, current, previous){
            if(current.viewClass) $scope.viewClass = current.viewClass;
        });
    }]);
    

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

When utilizing jQuery, I implemented this code but it does not display anything. I am unsure of the error within the code

When using jQuery, I implemented the following code snippet but it doesn't display anything. What could be causing this issue? // $.ajax({ // URL:"https://dog.ceo/api/breeds/image/random", // method:"GET", // ...

Navigate using history.push with user Logout Icon

Currently, I am utilizing a Material UI icon as a logout button in my project. Here is how I have implemented it: function logout(props:any){ localStorage.removeItem("token"); return( <Redirect to="/login" /> ) //props.history.push("/log ...

Complete circular gauge in Ionic

Encountering an issue when attempting to incorporate a complete circle Gauge/Gage in Ionic, as the gauge fails to display. Has anyone managed to successfully include a full circle Gauge in Ionic similar to this: Came across a GitHub repository that offer ...

Is there a way in AngularJS to trigger an event at a designated time?

I recently developed a webpage using AngularJS. I am looking to trigger certain actions on my webpage within a specified timeframe. For instance, If it is 2016-01-07 11:00:00, I want ng-show to execute some action. I am utilizing the Angular-timer for ...

Selecting elements dynamically with JQuery

Trying to use a jQuery selector within plugin code created by a 3rd party has proved difficult. When hardcoded, it works fine; however, when attempting to use variables for dynamic selection, the object cannot be found. The lack of id handles in the CSS c ...

When the browser back button is clicked, conceal the current div and reveal the previously hidden div

I'm faced with a situation where my website consists of multiple pages which I've achieved by displaying and hiding divs within a single html file. The issue I'm encountering is that the browser's back and forward buttons aren't fu ...

Is there a way to grab code from a different HTML page using JavaScript and jQuery when the user clicks on something?

After testing various codes for the intended purpose mentioned in the title, I have observed a peculiar behavior. The code from settings.html appears briefly and then disappears rapidly. Javascript: function load() { $("#paste").load("settings.html") ...

Exploring the data within $http in PHP

Currently, I am sending data to the server in the following manner: $scope.saveCaption = function(user_id) { var target = document.getElementById('toRender'); html2canvas(target, { onrendered: function(canvas) { $http({ ...

What is the most effective method for identifying the initial timestamp for each day, week, or month within a collection of timestamps?

I am dealing with a lengthy array of sorted timestamps representing stock price quotes. These timestamps have minimal resolution, meaning that each timestamp is at least 1 minute bigger than the previous one. However, there can be gaps during the day, espe ...

What is the process for resizing a texture render target following a window resize event?

My intention was to improve the texture quality, but instead of achieving my goal, I encountered an issue where the same texture is being stretched over a larger area, resulting in unwanted staircase artifacts. I tried updating various elements like camera ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

Having trouble with Angular router.navigate not functioning properly with route guard while already being on a component?

I am currently troubleshooting an issue with the router.navigate(['']) code that is not redirecting the user to the login component as expected. Instead of navigating to the login component, I find myself stuck on the home component. Upon adding ...

Generate Pagination in JavaScript using an Array of Elements

Is there a way to implement a Pagination System using JavaScript? Specifically, I need to display 10 products per page. I currently have an Array containing various products and my goal is to iterate through these products to display the first 10 on one p ...

Is there a way to verify the selection of all mandatory fields prior to concealing a div?

var count = 2; $('.next').click(function() { var requiredField = true; $(this).siblings('table').find('tbody tr:nth-child(' + count + ') td').each(function() { var element = $(this).find('center').f ...

Effective ways to replace an image using JavaScript

I am currently working on implementing a show/hide function, but I am encountering an issue with swapping the image (bootstrap class). The show-hide function is functioning properly; however, I am struggling to determine which class is currently displayed. ...

What is the best way to transmit a 500x500 2D Integer Array using Websockets?

I'm encountering an issue where I believe it may be too time-consuming to JSON.stringify and send data to each individual user. For example, if 4 people connect at the same time, the server will become stalled during array parsing, resulting in signif ...

The Node.js timestamp is later than the current date of the client

When storing data in MongoDB with the recording date, I utilize new Date() in Node.js and return that date with an AJAX response. To calculate the elapsed time from when the data was stored in MongoDB, I create a new date on the client-side. Then, I determ ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

Use JavaScript to dynamically populate dropdown list options with array elements

I attempted to populate a dropdown list with array elements using javascript, but I encountered issues. I referred to the following links for assistance: JavaScript - populate drop down list with array use a javascript array to fill up a drop down se ...