What is the best way to incorporate multiple class names based on varying conditions using ng class in Angular?

I am facing a challenge where I need to add 2 different class names under specific conditions to an element:

ng-class="(commentItem.comment | escapeHtml | direction)"

The first condition works well, as it retrieves the text content of the given HTML string using the "escapeHtml" filter and then determines the direction of the text using the "direction" filter. Now, I also need to add another class to the same element based on this condition:

ng-class="{'hidden': commentItem.isEditing}"

How can I combine both conditions within a single ngClass directive?

Note
I believe using the syntax {"exp1": condition1, "exp2": condition2} may not be feasible in this case because the filter in the first condition already returns the class name.

Answer №1

Check out this example on plnkr.

When it comes to using ng-class, the documentation explains how the argument should be evaluated:

The evaluation can result in a string that contains class names separated by spaces, an array, or a map of class names with boolean values.

Remember, the expression doesn't have to be just a literal string, map, or array. You can create a function that returns an array of classes like so:

ng-class="getClasses()"

You can then populate this array however you need within your controller. If you require filters, make use of the $filter service.

If you prefer not to use a controller function for handling view details, you can also pass an array to ng-class. For each element of the array, provide an expression that either returns a class name or an empty string:

ng-class="[!!redbg ? 'redbg' : '', 'gr' + 'een']"

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

Phonegap build seems to be malfunctioning

While attempting to develop my app on Phonegap using a plugin, I encountered an error specific to Android: "Error - Some official plugins must be updated when utilizing PhoneGap >= 4.0.0. It is necessary to upgrade the version of any plugins that may c ...

Issue with filtering of values returned by functions

I've been working with Angular's currency filter and I've run into an issue. It doesn't seem to be filtering the data that is returned from a function. I have a feeling that I might be missing something, perhaps it has to do with how th ...

Failure to Trigger Error Callback in Ajax Requests

I am encountering an issue with the error callback not being called when I pass the error function as an object parameter in a function. Strangely, when I define it directly within the ajax code, it works without any problems. var options = new Object(); ...

Adding associated documents into MongoDB from an Express application

My mongo db schema is structured as follows: users: {username:"", age: "", data: [ {field1:"", field2:""}, {field1:"", field2:""} ] } I am facing an issue with sending my user object to my express route for posting data to the database. ...

Utilizing Angular to bind a variable as an index for another variable within markup

Is it possible to render an array element in AngularJs using another scope variable as the index like this: {{array[{{index}}]}}? For example, I am attempting to do this (note the nested {{}}): <ion-item collection-repeat="item in prodataSelect" colle ...

Unlimited Angular Digest Loop Caused by promise.then()

The issue: The usage of this.promise.then(function(){}) function within a controller method appears to lead to an infinite digest loop on $rootScope, even though the returned value remains constant. It should be noted that removing the .then() line elimina ...

Matching email addresses using regex in Javascript

I am encountering an issue with the else if block in my Javascript code. It seems to be blocking all email IDs, even correct ones. Can someone assist with understanding what the match() function returns? I have tested the following scenarios: - Empty fie ...

Exploring the DOM in JavaScript: Searching for the final ancestor containing a specific attribute

Check out this example of HTML code: <div id="main1" data-attribute="main"> <div id="section2" data-attribute="subsection"> <div id="nested3" data-attribute="sub-subsection"> </div> </div> </div> <div id= ...

The Handsontable namespace does not include the _editors module in its exports

While following the documentation, I encountered an error when trying to integrate handsOnTable with my Vue 2 project using npm. The build process failed with the following message: ERROR in /node_modules/@handsontable/vue/types.d.ts(56,73): 56:73 Namesp ...

Create a Boxplot chart using Chart.js that dynamically adjusts the minimum and maximum values to allow for additional space on either

I am utilizing chartjs v2.9 for creating a boxplot and my code structure is as follows: function generateRandomValues(count, minimum, maximum) { const difference = maximum - minimum; return Array.from({length: count}).map(() => Math.random() * ...

Error: The method being called on this.props is not recognized as a valid function

I'm encountering an error in my code TypeError: this.props.* is not a function I've been trying to troubleshoot it but so far I haven't been able to identify what's causing the issue. I've attempted different methods, includin ...

Developing front-end libraries using the jspm workflow

What is the best way to convert a library written in TypeScript to ES5? While JSPM documentation focuses on web apps (such as with jspm bundle-sfx), the information I've found on Google seems more suited for a web app workflow rather than a library w ...

In order to ensure compatibility, the Bootstrap UI Angular Accordian and Rails template should always be structured with

I've been attempting to implement the accordion directive in my Rails application, but I keep encountering an error that causes my browser to crash. Upon using the example accordion directive, I received the following error message: "Template for dir ...

Error: Tranche codeigniter index not defined in the dependent dropdown

One of my drop-down menus depends on the selections made in two other drop-down menus. I have thoroughly checked the JavaScript, but an error keeps appearing in my logs: Undefined index: TRANCHE Below is the code snippet from my controller: public fu ...

Make sure the auto import feature in TypeScript Visual Studio Code Editor is set to always use the ".js" extension

At times, the auto-import completion feature includes the .js extension, but inconsistently. When this extension is missing in the TypeScript source, the emitted JavaScript file may encounter runtime issues like module not found error since the tsc compile ...

Is your jQuery .on function failing to properly detect click events?

Seems like I'm missing something here. Why is the .on function not functioning as expected in this code snippet? <html> <head> </head> <body> <button type="button" class="close" data-test="test">TEST BUTTON< ...

Apps hosted on Heroku are restricted from accessing CORS, even within the platform's domain

I've been struggling with this problem for a while now. My Nuxt app and service are both hosted on Heroku. After ditching cors(), I added the following code: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", '*&ap ...

Monitoring changes in input can be a crucial step in any data analysis

Is there a way to track changes in input using backbone? How it can be achieved in AngularJs: <div ng-controller="W3"> <input type="text" ng-model="val" > <p>{{val}}</p> </div> I would like the value of the in ...

Surprising array behavior encountered when using JSON.stringify on a particular site

I'm currently utilizing the JSON3 library, but I'm facing an issue where JSON.stringify is returning different results on a particular website. Unfortunately, the website requires login access, but I have included images for reference. If someon ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...