Troubleshooting ng-class functionality in AngularJS

I am attempting to utilize AngularJS in order to change the class name of a div element. Despite following the guidance provided in this answer, I am encountering difficulties as the class name is not updating in my view.

Below is the code from my view:

<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>

And here is the content of my app.js file:

var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);

app.controller("myApp", function ($scope) {
    $scope.class = "red";
    $scope.changeClass = function () {
        alert('a');
        if ($scope.class === "red")
            $scope.class = "blue";
        else
            $scope.class = "red";
    };
});
app.config(['$routeProvider',
        function ($routeProvider) {
            $routeProvider.
            when('/', {
                    title: 'Dashboard',
                    templateUrl: 'views/dashboard.html',
                    controller: 'authCtrl',
                    role: '0'
                })
                .otherwise({
                    redirectTo: '/login'
                });
        }
    ])
    .run(function ($rootScope, $location, Data) {
        $rootScope.$on("$routeChangeStart", function (event, next, current) {
            var nextUrl = next.$$route.originalPath;
            if (localStorage.getItem("serviceUserId") === null) {
                $location.path("/login");
            } else {

                if (nextUrl == '/') {
                    $location.path("/dashboard");
                }
            }
        });
    });

Can anyone help me identify what mistake I might be making and provide guidance on how to rectify it?

Answer №1

Keep in mind: The code provided is working perfectly fine for me as-is.

You can also achieve the same result with the following:

<div ng-class="{red: className === 'red', blue: className === 'blue'}">{{className}}</div>

If you prefer simplicity, you could use class="{{className}}" instead.


I consistently use className to avoid conflicts with JavaScript's reserved word class. This precaution helps prevent potential issues with certain minifiers, for example.

Answer №2

var app = angular.module('myApp', []);

app.controller("myCtrl", function ($scope) {
    $scope.className = "blue";
    $scope.changeClass = function () {
        alert('b');
        if ($scope.className === "blue")
            $scope.className = "green";
        else
            $scope.className = "blue";
    };
});
.blue {
  background-color: blue;
}

.green {
  background-color: green;
}

.blue, .green {
  width: 300px;
  height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <div class="{{className}}">{{className}}</div>
    <button ng-click="changeClass()">Change Class</button>
  </div>
</div>

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

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Getting the value from the object that holds the Provider/Consumer using React's Context API

Below is a demonstration using the Context API object with a library called 'react-singleton-context'. Check it out here. In my Menu.js file, I have the code snippet console.log(useSharedDataContext()). This displays an object containing Consume ...

Jest identifies an open handle when working with an Express application

For quite some time now, I've been grappling with a particular issue. It all started when I was conducting basic integration tests using a MongoDB database. However, I've minimized the code to its simplest form. The only thing left running is a s ...

Setting up user roles using Firebase Auth in NextJS application

Seeking a solution to implement a multi-level role system for my blog website. Currently utilizing Firebase Auth for authentication with email/password, but all users have the same posting/editing access. Looking to differentiate between Admins, Moderators ...

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...

Verify MVC Controller Authorization and respond with 401 Unauthorized to the AngularJS application

Currently, I have an AngularJS application that interacts with an MVC Controller to retrieve specific data. To ensure that users have the necessary permissions to execute certain actions on the controller, I've created a custom class called RBACAutho ...

Having trouble getting the Bootstrap modal form to submit when using Knockout's submit binding?

Check out my jsFiddle example by clicking here. I am currently working on a form within a bootstrap modal. The problem I'm facing is that the knockout submit binding doesn't get executed unless the user clicks on the submit input. It seems like ...

Upon invoking the useEffect function, the default value can be seamlessly established within the input field of the antd library

I have a function called loadProfile that I need to execute within the useEffect hook. When this function is triggered, I want the name Mario to be automatically displayed in the input field labeled name. How can I set this default value using the antd lib ...

What is the best way to switch between components when clicking on them? (The component displayed should update to the most recently clicked one

I am facing a challenge in rendering different components based on the navbar text that is clicked. Each onclick event should trigger the display of a specific component, replacing the current one. I have 5 elements with onclick events and would like to re ...

Express 4.13.4 appears to be disregarding the cookie's expiration date when the moment.toDate() function is used

I've been encountering an issue where I am attempting to set a cookie with a specific expiry date of 3 months, but the expiration is not setting correctly. Using momentJS, I created a date object for the desired time. The console confirms that the co ...

An error occured when attempting to read the 'status' property of an undefined value in node.js, express.js, and mysql

I recently started working with node.js and encountered a challenge in fetching data from mysql and sending it to an API response. Below is my setup: db.js: var mysql = require('mysql2'); var util = require('util') const pool = mysql ...

PHP Ajax Image Uploading and Storage

Is there a way to effortlessly upload an image and save it in the uploads folder without any page refresh? Not only that, but can we also have the uploaded image displayed on the screen within a designated div section? Unfortunately, I seem to encounter a ...

nodejs - pkg encountered an error: only one entry file or directory should be specified

I am currently facing issues with packing my simple cli node script using pkg. After running the command below: host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64 I encountered an error in the terminal: ...

Incorporate text into the URL of the image

Got a URL of an image like this: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg', and looking to add 240x240 within the URL. Current Url: https://lipsum.mobi/catalog/product/SE0229E/YG/AAA/4/1/SE0229E-YG-AAA-4.jpg Desire ...

"The Node.js program is unable to access the contents of the browser.js file when loaded in

After spending an unreasonable amount of time trying to debug this issue, I am still unable to resolve it. Currently, I am following a udemy tutorial where the instructor implements the same code provided below. However, despite my efforts, the code is not ...

Making sure to correctly implement email input fields in HTML5: Surprising behaviors observed with the email input type in the Chrome browser

Within the upcoming code snippet, a basic email validation is implemented. An input field's background color will display as white for valid emails and yellow for incorrect values. This functionality operates seamlessly in Firefox; however, in Chrome, ...

Transforming jquery code into Angularjs code

I am currently working on a jQuery method that adds a 'selected' class to table rows and handles click events. Here is the code: $('.niGridTable table tr').addClass('selected').end().click(function (event) { event = ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Storing multiple entries in a single MySQL cell along with JSON data

I have numerous folders named after different series on my website. Each series folder contains its own chapters, with each chapter containing images. As my website is a manga (comic) site, I want to store the paths of these folders and images in MySQL and ...

Using Jquery to send data with Ajax through a POST request to an endpoint

I'm having trouble sending data to an endpoint. The documentation specifies using a syntax like product[xx][amount] where xx is an id, but I can't seem to get it right. var postData = { product:153, amount:1 }; ...