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

Troubleshooting RequestError in Python Elasticsearch bulk operations: A step-by-step guide

I've encountered an error while trying to retrieve data from a website and store it in Elasticsearch. The issue seems to be with my document not being correct. I followed the bulk elastic documentation but I'm still struggling to resolve this. Is ...

Relay information between requests using a RESTful API and various data formats, such as JSON, XML, HTML

In a scenario with a REST API that can deliver JSON, XML, HTML, and other formats, the default response for browsers without JavaScript enabled is HTML. This API utilizes tokens for authentication and authorization. Within a traditional website project, t ...

Experiencing a problem with my JavaScript code in Node.js due to an asynchronous issue arising when using a timeout

My goal with this code is to retrieve JSON questions and present them to the user through the terminal. The user has 5 seconds to respond to each question before the next one appears. However, I encountered an issue where the next question times out automa ...

Exploring the depths of nested objects within my Rails JSON data structure

I am looking to structure a nested JSON format for my Event model that resembles the following: "event": { "quiz": { "name": "", "desc": "", "events": [ { "name": "general quiz", "desc": "" }] }, "dance": { "name": "", ...

Utilizing AngularJS to display the contents of a MongoDB collection

I have a set of sessions that I want to print out individually using AngularJS. This is my code : collection.find().toArray(function(error,data){ if (error) { // Pass the error to the error handler console.log("Error :" + erro ...

Safari is not properly rendering a React/Next.js website (showing a blank page)

Recently, I've been facing a frustrating bug on my Next.js website. When I try to open it in Safari, there's a 50/50 chance that it will either load correctly or show a blank page with faint outlines of components but no text. This issue occurs o ...

What is the best way to include additional values in a NewtonSoft JObject?

I am currently using NewtonSoft JSON.Net for my project and I have a JObject that I need to dynamically add and remove items to from my code. Here is an example of the JSON I am working with: { "IgnoredInterests": [ { "Id": 1, "Name": ...

What is the process for importing extensions and files in Visual Studio Code?

Nodejs development utilizing (--experimental-modules) Current visual studio code intelligence import example: import config from "./config"; However, it should be imported as: import config from "./config.js"; An error is encountered without the . ...

Encountering problem on Heroku: Bower resolver is missing

Are you familiar with the concept of Javascript fatigue? I have recently become aware of it. Although I am not a javascript developer, I use Node and Angular for a side project on my server. All my node packages are installed using npm and my angular pa ...

Tips for interpreting JSON content within a C# HttpPost function

I need assistance with extracting data from a JSON body and then displaying it in an HttpPost method using C#. The JSON payload includes: { "name": "John", "age": "20" } [HttpPost] public async Task<IAct ...

What is causing the jqplot meter gauge problem with the error message "c.jqplot is undefined

I'm encountering an issue and seeking some guidance. I am relatively new to this, so navigating the problem proves challenging. I'm attempting to utilize jqplot's meter gauge according to the documentation, but it doesn't seem to be fun ...

When iteratively utilizing the setValue() function, an unintentional occurrence of an 'Uncaught error' is encountered

I encountered an issue while trying to update a spreadsheet upon submitting a form. The problem is that after pressing the submit button, the remaining commands are not being executed properly. As a result, I see an error message in the console saying "U ...

The compression feature in express.js middleware is not functioning correctly

The middlewares set up in my app are as follows: app.use(express.favicon(__dirname + '/static/public/images/favicon.ico')); app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser('S ...

Steps for appending ng-repeat elements to an array

Currently, I am in the process of developing a shopping cart feature that utilizes ng-repeat to loop through a JSON object list. One of the functions I've created is addToBag, which aims to add items to an empty array for display on the checkout page ...

The action 'onDeleteClick' cannot be executed as the property is undefined

Why is the onDeleteClick function working on the first <div>, but returning undefined on the second one? I am able to access the reference of this, but when clicking, it shows "onDeleteClick of undefined". I am confused as to why the onDeleteClick f ...

What is the best way to modify an array's property in order to achieve the desired outcome when using json_encode?

Expected Result ['#ff0000','#4caf50','#4caf50','#4caf50','#00bcd4','#00bcd4','#4caf50','#4caf50'] The output I am receiving is as follows: ["'#ff0000','#4caf5 ...

Generating JSON output from Powershell in a customized manner

I have developed a script that scans machines to gather information about software versions installed and then displays the data across multiple VMs. My goal is to integrate this script into a Dashboard platform that we use, but the provider has specific ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...

You are unable to select the element in IE if there is an image in the background

Apologies for coming back with the same question, as I realize now that I was not clear in my explanation yesterday. You can find the codepen here (please note that it may not open in IE8). My issue is with dragging the 'move-obj' element in IE b ...

The function is not specified

Currently, I am in the process of implementing a login system using nodejs. My goal is to define a global function outside of a module and then call it multiple times within the module. However, I am encountering an issue where it always returns undefined, ...