Using AngularJS to implement conditional ng-class with multiple matches for a single option

I encountered an issue with the following code snippet:

<span class="label"
              ng-class="{
              'label-success': resp.level == 'A1',
              'label-success': resp.level == 'A2',
              'label-warning': resp.level == 'B1',
              'label-warning': resp.level == 'B2',
              'label-danger': resp.level == 'C1',
              'label-danger': resp.level == 'C2',
              'label-default': resp.level == 'This word was not found',
              'label-default': resp.level == 'The word level is not known'}">{[{resp.level}]}</span>

It seems that the code is not functioning properly due to multiple matches for the same option. The revised code works as intended:

<span class="label"
              ng-class="{
              'label-success': resp.level == 'A1',
              'label-warning': resp.level == 'B1',
              'label-danger': resp.level == 'C1',
              'label-default': resp.level == 'The word level is not known'}">{[{resp.level}]}</span>

Questions:

  • What could be causing this issue?
  • Any suggestions on how to resolve it?

Answer №1

The reason the first one isn't functioning is because we're creating an object with a duplicate key, which is not permitted.

<span class="label"
          ng-class="{
          'label-success': (resp.level == 'A1' || resp.level == 'A2'),

          'label-warning': (resp.level == 'B1' || resp.level == 'B2'),

          'label-danger': (resp.level == 'C1' || resp.level == 'c2'),

          'label-default': (resp.level == 'This word was not found' || resp.level == 'The word level is not known')
          }">{[{resp.level}]}</span>

Answer №2

Combine your conditions using the OR operator:

<span class="label"
          ng-class="{
          'label-success': resp.level === 'A1' || resp.level == 'A2',
          'label-warning': resp.level === 'B1' || resp.level == 'B2',
          'label-danger': resp.level === 'C1' || resp.level == 'C2',
          'label-default': resp.level === 'This word was not found' || resp.level === 'The word level is not known'}">{[{resp.level}]}</span>

Alternatively, you can also check only the first letter of the level.

<span class="label"
          ng-class="{
          'label-success': resp.level[0] === 'A',
          'label-warning': resp.level[0] === 'B',
          'label-danger': resp.level[0] === 'C',
          'label-default': resp.level[0] === 'T'}">{[{resp.level}]}</span>

Answer №3

Referencing the definition outlined in RFC 4627:

An object is enclosed within a set of curly brackets and contains pairs of name/value combinations. Each name is designated as a string and is followed by a colon separating it from its corresponding value. Values are separated by commas, with names being unique within the object.

In the context of your situation, where the ng-class attribute consists of an object argument, duplicate names are not allowed. However, you can utilize logical operators such as 'or' as demonstrated below:

ng-class={'active': someVal === 1 || someVal === 2}

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

Utilizing Smoke.js within a PHP environment

I created a PHP function to validate HTML form fields. When an error occurs, the code below will display an error message using JavaScript "alert": echo '<script type= "text/javascript">alert("account not found in database")</script>&apo ...

Navigating in Angular JS using $location function

I'm facing an issue with navigating between web pages using Angular JS. The first web page is index.html, followed by main.html. Additionally, there is a myscript.js file and style.css, although the latter is not relevant to this problem. My goal is t ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

Unable to modify border color for Material-UI OutlinedInput

Having some trouble changing the border color of a v4.13 MaterialUI Outlined Input. No luck with CSS overrides. Tested multiple CSS rules targeting different elements, such as select and OutlinedInput. Here are my latest attempts. What am I missing? cons ...

Attempting to add color to a cube using Three.js

Attempting to apply three different colors to a cube in three.js, it appears that there may be a limit on the number of THREE.DirectionalLight objects that can be added to a scene. The lack of mention of such a limit in the documentation has raised questio ...

Implementing a dynamic navbar in Vue.js using Firebase authentication

I've been diving into a Vue.js project that allows users to sign up and log in. I've incorporated Firebase Authentication for the login and sign up functionality. Successfully, I've implemented the feature where the navbar state changes: whe ...

What is the best method for aligning buttons in a row with all the other buttons?

I have been attempting to display two buttons, id="strength" and id="minion", when a certain button, id="expandButton", is clicked. I want these two buttons to be positioned on either side of the button that triggers their cre ...

NextJS application having trouble re-rendering after state update

Although this question is commonly asked, none of the solutions seem to work for me. I am facing an issue where updating a variable using useState does not trigger re-rendering of any components. The scenario involves POSTing data using NextJS API Routing ...

The combination of jQuery, using .load method in javascript to prevent scrolling up, making XMLHttpRequest requests, updating .innerHTML elements, and troubleshooting CSS/JS

While utilizing this code, CSS and Javascript are disabled (only HTML loads): function loadContent(limit) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status ...

My Next.js application does not display an error message when the input field is not valid

I've recently developed a currency converter application. It functions properly when a number is provided as input. However, in cases where the user enters anything other than a number or leaves the input field empty, the app fails to respond. I aim t ...

I relocated the navigation HTML code to a new file and as a result, the JavaScript functionality is

After successfully implementing the hamburger icon animation in my navbar using JavaScript, I decided to move the nav code to a separate file for better organization. However, the decision resulted in an error where clicking on the burger icon returned a m ...

verify whether the image source has been altered

There is an img tag displaying the user's avatar. When they click a button to edit the image and choose a new one, the src attribute of the img changes to the new image src. How can I detect when the src changes? Below is the code for the button tha ...

Branding image from Bootstrap overlapped with a container situated below the navigation bar

I'm having trouble adding a 400 x 100 png logo as a Navbar Brand image in Bootstrap 5. The logo is appearing too large, and even when I try to resize it, it still overlaps the black container and text input box below the Navbar in desktop view. On mob ...

Generate a revised object from a function and return it to the caller

What is the most efficient way to update and return a new object from a function? I came up with this function: export const addItemToCart = (currentCart, item) => { const { name, ...otherProps } = item; // if the item is already in the cart if ...

Is there a method in Kalendae js that automatically triggers the closing of the calendar after a date has been selected?

Currently, I am using Kalendae from https://github.com/ChiperSoft/Kalendae and I have to say it is fantastic. The best part is that I don't have to worry about dependencies. By default, the calendar pops up when a text box is selected and updates the ...

Issue with React / Express failing to route links accurately

Currently, my React project is functioning well except for Express. I have been struggling to find comprehensive tutorials on implementing correct routing with Express in a MERN stack application. I have come across some Stack Overflow posts, but none of ...

Why is the raycaster unable to detect the object that has been loaded in three.js?

I am new to THREE.js. I would like to implement a feature where clicking the mouse selects a loaded .obj object in the scene, highlights it by making it half transparent, and then allows the object to follow the mouse as it moves. Subsequently, another cli ...

The v-select function organizes data based on the content of "item-text"

I created a v-select component using Vuetify, and I am wondering how I can sort the names of the items from largest to smallest within this v-select? <v-select v-model="selectedFruits" :items="fruits" label="Favorite Fruit ...

What could be causing the WebdriverIO browser object to unexpectedly exit my loops?

Each time I try to invoke a method using WebDriverIO's browser object, it abruptly escapes from the current loop I'm in. Upon inspection with the debugger, it is evident that no other code within the loop is being executed. Despite the fact that ...

The mapStateToProps function is returning an undefined value

import React, { Component, Fragment } from "react"; import { connect } from "react-redux"; import { login, logout } from "./redux/actions/accounts"; import Home from "./Home"; import Login from "./Login"; class ToggleButton extends Component { render() ...