Using a variable to assign classes in Angular

Is it possible to use Angular to apply a class to a form field after it has been edited? The issue arises when trying to set the class name as a variable value rather than a string. Below are two code snippets - one that works and one that doesn't.

A ) This works:

<select ng-model="testModel" 
    ng-options="foo for foo in someList" 
    ng-change="testSwitch = 1" 
    ng-class="{'some-classname' : testSwitch }">

B ) This also works:

<select ng-model="testModel" 
    ng-options="foo for foo in someList" 
    ng-change="testSwitch = 1" 
    ng-class="{testVar}">

where:

$scope.testVar = 'some-classname';

C ) But this does not:

In view:

<select ng-model="testModel" 
    ng-options="foo for foo in someList" 
    ng-change="testSwitch = 1" 
    ng-class="{testVar : testSwitch }">

Does anyone know why this is happening or have any other possible solutions?

Answer №1

To implement conditional styling, you can employ the ternary method:

<select ng-model="exampleModel" 
    ng-options="item for item in anotherList" 
    ng-change="switchVar = 1" 
    ng-class="switchVar ? varStyle : ''">

Answer №2

If you want to assign the class as a variable in angularJS, avoid using the conditional approach with the : and boolean.

Instead of:

<select ng-model="testModel" 
    ng-options="item for item in itemList" 
    ng-change="testSwitch = 1" 
    ng-class="{testVar : testSwitch }">

Stick to option B and define the different class name in the controller like this:

$scope.testVar = testSwitch ? 'custom-class' : '';

This approach should work without any issues.

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 event.altKey property seems to be blank and not returning any information

I've been attempting to display or hide a div when the Alt button is pressed. I've set up a keypress event listener and used event.altKey to check if the Alt/Option key is being pressed. However, this approach didn't yield the desired result ...

Automatically updating values using jQuery AJAX

My table consists of rows structured like this: <tr> <td> <div class='tempo' id='<?php print $id;?>'></div> </td> </tr> In addition, I am utilizing the following jQuery function: var ...

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Angular function triggered when "onchange" directive is called

Here is a specific question about passing an angular callback into a JavaScript directive.... see below. (trying with product.id through the onchange event) $scope.fileNameChanged = function(folder, id){ console.log(folder + " " + id); } <d ...

Increasing the grid size in React Bootstrap 5 for added flexibility

Customizing React Bootstrap Sizes WPW Container Max-Width sx < 576px - none sm > 567px - 540px md > 768px - 720px lg > 992px - 960px xl > 1200px - 1140px xxl > 1400px - 1320px Desiring a New Size Category: I am interested in ad ...

Implementing Angular 4 to fetch information from a JSON file

As a beginner in Angular, my current task involves loading data from a JSON file upon click, which I have successfully achieved so far. However, I am facing an issue where I'm unable to load the first JSON object before clicking, meaning that I want ...

sending an array variable to ajax in CakePHP

I am currently working on creating a feature similar to this where users can select multiple conditions for their search. My approach involves populating an array with the selected conditions and passing it through ajax to make a request. Below are snippet ...

When should abstract state mode and nesting/named views be utilized in angular UI Router?

Having trouble understanding this from the documentation: In my scenario, I am working on a large SPA with multiple "widgets" or "apps" on a page - each one having a controller, data, and template. Ideally, each of these should be considered as a view. Cu ...

Creating a spinning or swinging motion using scriptaculous shake

I want to create a unique hover effect where the item doesn't shake from side to side, but instead smoothly slides like a clock pendulum moving from 180-90 degrees. I'm not certain about the exact numbers right now. Is this achievable with Script ...

What is the best way to iterate through values within my JSON document?

Let's say I have a JSON file and I want to iterate through the values in this manner: var myModel = {"id": 0, "date": "2014-10-28", "amount": 1111, "productId": "2", "description": "Cash"}; for (value in myModel) { //element(by.model(key) ...

Having trouble viewing the data on my D3 graph

As I attempt to replicate a D3 template, the only variation being that I am extracting the JavaScript and JSON data from my Mac. Despite this, upon opening the HTML in Chrome, the data is not visible. It seems that Stackoverflow is not recognizing my HTM ...

Using Array.filter with multiple conditions

I am faced with a scenario where I need to filter and categorize an array of objects based on multiple conditions. The challenge arises from the fact that there are more than one condition, and I want the array to be split into several groups accordingly. ...

The TextField is currently unable to be edited because of an Uncaught TypeError stating it is not iterable

Currently, I am fetching data from an API and updating TextFields with it for display. My goal is to allow users to edit the data shown in these TextFields, but I keep encountering a Uncaught TypeError: prev.fields is not iterable error whenever I attempt ...

Angular protects routes by using tokens stored in cookies

I typically store the user token in local storage and use the "token" key in local storage as a method to protect certain routes in my application. If the key is present, I allow the user to access the page, but if it's not, I redirect them to the log ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

Problems arise when using $(window).width() in conjunction with scrolling functionality

I am attempting to ensure this code only activates when the device window exceeds 960px and triggers when the window scrolls down 700px. The second condition is functioning as intended, but the first condition is not working properly. The code functions f ...

Navigating JSONP using jQuery

I'm encountering an issue where I can see the correct response in Firebug, but I'm unable to access the data it returns. I need some guidance on how to achieve this. Specifically, I'm attempting to place the timestamp of an entry into a div ...

Tips for customizing the color of the inner components in the toolbar of MUI DataGridPro

Is there a way to customize the color of the inner components in mui toolbars? For example, I have added columns and when I click on them, a filter box pops up with default colors for switches and buttons. How can I change these colors to match my theme? ...

Managing numerous requests simultaneously without causing one to delay or block the others

I am facing challenges when it comes to managing multiple client requests. Ideally, each route should be handled asynchronously, but I am struggling to handle one request after another without the previous one interfering with the next one. In the code sni ...