Is it possible to combine ng-class with conditional expression and ng-class with string syntax in a single statement?

To assign classes based on the ngRepeat index, I am using ng-init="myIndex = $index". With this setup, I can apply classes like color-0, color-1, color-2, etc. by using ng-class='"color-" + myindex'.

Furthermore, I need to add a different class if an element is selected. For this purpose, I am using

ng-class="{'selected': element.selected}"
.

While both ngClass directives work independently, I am struggling to combine them in the same ngClass declaration.

I have tried variations like

ng-class="'color-' + myIndex, {'selected': element.selected}"
in various ways, but keep encountering the error:

Error: [$parse:syntax] Syntax Error: Token ',' is an unexpected token at column 19 of the expression ['color-' + myIndex, {'selected': element.selected}] starting at [, {'selected': element.selected}].

Answer №1

Using different notation options:

ng-class="['color-' + myIndex, element.selected ? 'selected' : '']"

or:

ng-class="['color-' + myIndex, {true: 'selected'}[element.selected]]"


Alternative approach with object notation:

ng-class="{selected: element.selected, {{ 'color-' + myIndex }}: true}"

or:

ng-class="{selected: element.selected}" class="{{ 'color-' + myIndex }}"

Please keep in mind that the last method mentioned above is not advisable as it could interfere with AngularJS classes being properly added (e.g. ng-scope..).

Answer №2

For those utilizing AngularJS version 1.4 or higher, there is an additional approach available:

ng-class="['color-' + myIndex, {'selected': element.selected}]"

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

Tips for accessing user input in JavaScript functions

In my ASP.NET code, I have created a dynamic image button and panel. Here is the code: Panel panBlocks = new Panel(); panBlocks.ID = "PanBlockQuestionID" + recordcount.ToString(); panBlocks.Width = 1300; panBlocks.Height = 50; panBlocks.BackColor = Color. ...

How can I make sure to consider the scrollbar when using viewport width units?

I've been working on developing a carousel similar to Netflix, but I'm facing an issue with responsiveness. I've been using a codepen example as a reference: Check out the example here The problem lies in the hardcoded width and height use ...

What is the best way to retrieve the value of an UL LI element using jQuery

I'm struggling to retrieve the value of a ul li listbox in a function, and I can't seem to figure out how. Here is my code: <ul class="dropdown-menu" id="newloc"> <?php $res_add = DB::table('res_br')-& ...

Definition of Stencil Component Method

I'm encountering an issue while developing a stencil.js web component. The error I'm facing is: (index):28 Uncaught TypeError: comp.hideDataPanel is not a function at HTMLDocument. ((index):28) My goal is to integrate my stencil component i ...

Can you please explain the differences between "resolved" and "rejected" in a deferred object within jQuery?

Recently, I inquired about a refreshing page solution if an internet connection is available on Stack Overflow. The user @Fabrizio Calderan provided an elegant approach utilizing deferred object implementation: setInterval(function() { $.when( ...

Generating a fresh instance from a pre-existing object using JavaScript

Currently, I am facing a challenge from devchallenges.io known as the Shoppingify challenge. After carefully reviewing the prompt, I started working on creating a model that should have a specific format when a request is submitted. { "user": 1 ...

Development of an AngularJS progress bar feature

After setting up a http get method in my controller to retrieve data from a json and display it in the view, I decided to add a progress bar. However, the progress bar continues running even after the data has been loaded. How can I make sure the progress ...

Date selection tool in Bootstrap showing blank field

I am currently working on implementing a bootstrap datepicker to update layer dates on my website. However, I am facing an issue where the calendar dropdown does not appear when I click on the datepicker box and instead it just shows an empty box. My goal ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

Issue with `npm run watch` failing to compile when the data source is turned

Currently, I am faced with a challenge while working on Laravel and utilizing various node packages for development. The issue at hand is my limited internet connectivity. Every time I attempt to execute npm run watch, it refuses to initiate unless I am c ...

What is preventing me from deleting cookies on Express?

Whenever a new user is registered, the number of cookies just keeps increasing endlessly. userRoutes.js: const { registerUser, loginUser, registerVerify } = require("./userController"); const express=require('express') const router=ex ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

The Angular filter is failing to display the category value

My issue lies in adding a filter to display categories, as my setCurrentCategory function is not showing any value but instead displaying 'undefined'. The goal is to show the category for each person. I'm using ng-click to pass to my functio ...

Fulfill the promise once all map requests have been completed

Currently, my focus is on developing a bookmark page that retrieves bookmark results with the respective restaurant IDs. Once the response is mapped, I populate an array with objects. My objective is to ultimately resolve the entire array in order to mani ...

Form with missing input fields submits nothing to the server

I created a Node project with a single view page for users to access information. When I use an HTML form to send data, the content is empty. I have verified multiple times using Postman that the information is being saved successfully when sent with the P ...

How can I render just one event instead of all events when using the eventRender callback function?

I am currently working on adding an event to my calendar using a JSON format with specific attributes like id and start time. Here is what I have tried so far: $('#calendar').fullCalendar('renderEvent', my_event); $('#calendar& ...

Achieving successful functionality with position:relative in IE9

Having difficulty with the position: relative property in IE9. Check out this demo for reference: <div style="overflow:scroll;height:120px;"> <table id="table" width="100%"> <tr style="position:relative;background-color:#1b72a4;"> ...

Decide whether to fulfill or deny a Promise at a later time in

When working on an Angular2/TypeScript project, a dialog is shown and the system returns a Promise object to the caller. This Promise will be resolved after the user closes the dialog. The interface of the Promise class does not include methods like resol ...

How can I retrieve the value from the input field using vue.js?

I am currently utilizing the vue-js-toggle-button library. While I understand that I can access the value inside the name using $refs, the issue arises as I have 3 toggle buttons and cannot set a Ref because I want to retrieve the name value dynamically i ...