Utilizing ng-class for dynamic routing and controlling

I am currently in the process of developing a dynamic framework using AngularJS. My plan involves allowing users to add new templateUrl and controller from a JSON file, like the one shown in templates.json:

{
  "pages" : [
    {
    "name"        : "home",
    "tempUrls"    : "views/home",
    "controller"  : "HomeController"
    },
    {
      "name"        : "about",
      "tempUrls"    : "views/about",
      "controller"  : "AboutController"
    },
    {
      "name"        : "contact",
      "tempUrls"    : "views/contact",
      "controller"  : "ContactController"
    }
  ]
}

Our task is to create the controller and templateUrl for each page in AngularJS based on the information provided in the JSON file, such as hours.js:

var hours = angular.module('hours', ['ngRoute']);

var $routeProviderReference;
var currentRoute;
hours.config(function($routeProvider){
    $routeProviderReference = $routeProvider;
})
.run(['$route', '$http', '$rootScope', function($route, $http, $rootScope){
    $http.get("templates.json").success(function(data){
        var loop = 0, currentRoute;
        for(loop = 0; loop < data.pages.length; loop++){
            currentRoute = data.pages[loop];
            var routeName = "/" + currentRoute.name;
            $routeProviderReference.when(routeName, {
                templateUrl: currentRoute.tempUrls,
                controller : currentRoute.controller,
                resolve: {
                    param: function()
                    {
                        return currentRoute.resolve;
                    }
                }
            });
        }
        $route.reload();
    });
}]);

hours.controller(currentRoute.controller, function($scope){
    $scope.pageClass = 'page-' + currentRoute.name;
});

Next, we have the index.html file:

<div ng-class="{{pageClass}}" ng-view></div>

Before converting to a dynamic version, here is the static example using AngularJS:

var hours = angular.module('hours', ['ngRoute']);

hours.config(function($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl: 'views/page-home.html',
            controller: 'homeController'
        })
});

hours.controller('homeController', function($scope){
    $scope.pageClass = 'page-home';
});

If anyone can provide assistance, it would be greatly appreciated!

Answer №1

My experience with working with ng-class has been consistent in using the format with single curly braces. The ng-class directive supports multiple formats, but I prefer the one with the braces.

ng-class="{ myClass: ExpressionThatResolvesTrueOrFalse }"

When the expression evaluates to true, Angular will apply the myClass class to the element. If it resolves to false, the class will not be added. Angular will monitor changes in the expression value during the scope digest cycle.

In contrast, the model format does not require braces and follows a simpler syntax like:

ng-class="pageClass"

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

Performing a wildcard search to replace deep child values and merging them back into the original JSON using JQ

Can someone help me with a JSON manipulation issue similar to the one discussed in this post about Unix jq parsing wildcards? I want to change the value of "c": "text1" to "c": "newtext", while also merging the modif ...

Using Java's Jackson streaming API to establish a connection using TCP sockets

Having trouble with sending and receiving JSON objects over a socket connection. The parsing is not working correctly on the server side. This project marks my first attempt at Java programming. Below is my socket class: static class CheckerSocket im ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

Managing numerical data in a CSV file using JavaScript and Google Visualization Table

A JavaScript snippet provided below will load a CSV file named numericalData.csv, which contains headers in the first row and numerical values starting from the second row. The data is then displayed using a Google Visualization Table. I am looking to con ...

Instructions for implementing tooltips on a pie chart slice when hovering with the mouse pointer, using the canvas

var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var cw = canvas.width; var ch = canvas.height; ctx.lineWidth = 2; ctx.font = '14px verdana'; var PI2 = Math.PI * 2; var myColor = ["Gr ...

Setting a value to ng-model in AngularJS

I am having some trouble using ng-model with multiple dropdowns. My goal is to have the first select option set to empty, which should then make the rest of the dropdowns also show the empty option. <select ng-model="ddl"> <option></option ...

What is the best way to retain the leading zeros when creating a new Number() in JavaScript?

Hey everyone, I'm running into some issues with this specific function. const incrementString = str => { if (!str.match(/[\d+]$/)){ return str += 1 } else{ return str.replace(/[\d+]$/, match => new Number(match) + 1) } ...

"Clicking and typing on the form data for the ng-click and ng-keypress

When I click a button, I want to send user input data to be displayed on the screen. However, when I click the button, it simply moves to the next value without collecting the information and displaying it on the screen. Strangely, if I press ENTER, it wor ...

What potential problem is arising from Jest's use of "transformIgnorePatterns" and how does it impact importing scoped CSS in a React application?

Currently facing a challenge with Jest testing in my React application following the addition of transformIgnorePatterns to the Jest settings. The default settings I included in the "jest" section of the root package.json file are as follows: "transfo ...

An effective method for binding items permanently while still being able to update the entire selection

Imagine a scenario where a list of 1000 items is displayed using infinite scrolling. Each item on the list includes a person's firstName, lastName, and mood for simplicity. Initially, I didn't want to constantly listen for updates. Fortunatel ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

Enhancing Your Website with Dynamic Images using AngularJS (ng-class)

Looking to swap between 3 image variations based on different event states such as 'current', 'onClick', and 'onHover'. Wondering if Angular's 'ng-class' can be used with images to add onClick and onHover as Jav ...

Tips for making SoapUI json requests compatible with German umlauts

In our team project, we heavily rely on SoapUI for handling various interfaces. Recently, we encountered an issue related to German special characters known as umlauts. When attempting to send a POST request with a Json body containing a German umlaut, we ...

Utilize jQuery to dynamically load and assign unique ids to elements within an array

I am seeking assistance with dynamically assigning unique IDs to elements in an array using JavaScript and jQuery. I am new to these languages and need some guidance. function assignIds() { var elementIds = ['name', 'lname', ' ...

What is the best way to find the difference between two time moments using Moment

Hello everyone, I could really use some assistance with Moment.js. I have two input fields, one labeled Start and the other labeled Stop. start = moment().format('LT'); // This works when I click on the play button stop = moment().format(' ...

Creating two separate divs that can scroll independently while also limiting each other's scroll depth can be achieved by utilizing

I am attempting to replicate the unique scrolling feature seen on this particular page. Essentially, there are two columns above the fold that can be scrolled independently, but I want their scroll depths to be linked. When a certain depth is reached whil ...

The conditional statement does not align with my Regular Expression

I'm experiencing a peculiar issue with my regular expression matching in the code snippet provided. Even though the alert confirms a match between the strings, the if statement fails to trigger. Any insights on why this might be happening? Appreciate ...

The issue with jspdf is that it is failing to generate PDF documents of

I'm currently developing a resume builder app using ReactJS. One of the functionalities I'm working on is enabling users to download their resumes as PDFs. However, I've encountered an issue with the generated PDFs when using jsPDF. The down ...

Using Vue Router to set a variable as a key for an object in JavaScript

In my current project, I am attempting to pass a variable as the parameter to vue-router in order to dynamically set it. The code snippet below demonstrates what I am trying to achieve: <router-link :to="{ name: notification.name, (notification.pa ...

Refreshing the dropdown selection to a specific option using AngularJS and either JavaScript or jQuery

Currently, I am facing an issue with resetting the select tag to its first option. I have implemented Materialize CSS for styling purposes. Despite my efforts, the code snippet below is not achieving the desired outcome. Here is the JavaScript within an ...