Using the ternary operator along with equality statements within ng-class

I'm trying to enhance an element with the following ng-class attributes:

<div ng-class="a ? 'class1' : 'class2'"></div>
Now, I want to include another ng-class statement: ng-class="class3: b !== c". How can I merge these ng-class statements effectively? I've attempted
<div ng-class="{a ? 'class1' : 'class2, class3: b !== c"></div>
as well as
<div ng-class="(a ? 'class1' : 'class2') + ' ' + (class3: b !== c)"></div>
, but neither seem to be working. Any suggestions?

Answer №1

I personally prefer using a specific syntax for ng-class in order to clearly indicate which classes are being added, rather than relying on the ternary operator:

<div ng-class="{'class1' : a, 'class2' : !a, 'class3': b !== c }"></div>

Alternatively, if you prefer using the ternary operator, you can do so like this:

<div ng-class="(a ? 'class1' : 'class2') + ' ' + (b !== c ? 'class3': '' )></div>

The reason your solutions may not have worked is likely because you attempted to mix the two different syntax styles (with and without curly brackets).

Answer №2

It is possible to achieve this without using a ternary operator by utilizing the following code snippet.

<div ng-class="{'class1' : a, 'class2' : !a, 'class3': b !== c }"></div>

Answer №3

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

app.controller('ctrl', function($scope){
$scope.a = 1;
$scope.c = 10;
$scope.b = 89;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<style>
.class1{
font-size:18px;
}
.class2{
color:orange;
}
.class3{
color:blue;
}
</style>
<body ng-app="exApp" ng-controller="ctrl">
<p ng-class="a ? 'class1' : 'class2'">Hi..Used Ternary Operator</p>
<p ng-class="{'class3': b !== c, 'class1' : !a, 'class2':a, }">Hi!...Without Ternary Operator</p>
</body>

ng-class=" {className1: checkIftrue, className2: otherCondition}" 

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

Challenges with handling multiple concurrent AJAX requests in jQuery

The challenge here is that the application needs to make multiple requests to a web service using $.ajax, but the number of times these requests need to be made depends on the user. Due to this dynamic nature, it appears that using $.when might not be suit ...

Display header right button based on a condition in React Native using React Navigation

I am looking to conditionally display the Entypo new-message icon in the top right corner of the header based on a boolean variable (if true, then show the icon in the header). Here is a snippet of code where this functionality can be replicated. Thank y ...

What is the best way to delete a subdocument from a main document when either condition x is true or condition y is true?

A subdocument referred to as Bets is embedded into an array of a property on another model called Users. When a user removes a friend, all associated bets with that specific user should also be deleted from the User document (the user who was friends with ...

Transferring previously obtained data to templateProvider within AngularJS

I'm currently working with AngularJS 1.3 and UI-Router. I have a state set up with a resolve and a templateProvider. My goal is to utilize the data fetched from the database in the resolve within the templateProvider without having to make duplicate ...

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

Using Vue.js, separate the values that are separated by commas

I am looking to extract values from a string and store them in an array for use in displaying values in a dropdown format within Vuejs String str = "abc,123,676,uuu". Once I have iterated through the values <li v-for = "value i ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Exploring the World of Three.js: Modifying Facial Structures

Can anyone help me figure out how to obtain the average x, y, z coordinates of a specific face in three.js? Or, could someone guide me on extracting the individual x, y, z coordinates of the three vertices that compose a face and averaging them? Currently ...

Is there a way to retrieve breaks and white spaces from a database in React JS with the help of Laravel?

Hello, Stack Overflow! I'm having trouble saving text from a textarea to the database. How can I preserve line breaks and spaces when retrieving the text from the database? Thank you for your help and guidance. Below is the frontend code for the t ...

Issue with Angular's ngOnChanges Lifecycle Hook Preventing Function ExecutionWhen attempting to run a function within Angular's ngOn

In the midst of my evaluation process to ensure that specific values are properly transmitted from one component to another using Angular's custom Output() and EventEmitter(), I am encountering some issues. These values are being sent from the view of ...

Exploring JavaScript and mastering it through Visual Studio Code and Node.js for debugging and learning

I am currently using Visual Studio Code to practice and test my Javascript skills. In order to activate debugging features, I have installed Node.js and selected "node" in the launch.json file. What's confusing me is that the outcome of my code seem ...

Is my approach to managing errors appropriate when using async/await functions in conjunction with Mongoose?

When working on my website, I heavily rely on asynchronous functions to manage various aspects such as creating articles, setting up administrator accounts, rendering views, and more. I have a routine of creating all the necessary async functions within a ...

In ASP.Net, looking to execute JavaScript once the update panel finishes loading

Is there a way to trigger a JavaScript function only when the update panel has completely loaded, rather than on the initial page load? I want to be able to scroll once the update panel is fully loaded. If anyone has any suggestions or solutions, please l ...

Guide to implementing an animate-on-scroll feature for data retrieved in a React application

Background: I am trying to implement an AOS-effect on multiple divs that are populated with data from a server and rendered after the initial load: import {useEffect, useState} from "react"; export const Test = () => { const [data, setData] = u ...

What is the best way to append an element to the end of an array in Angular JS?

One of the arrays that I am working with in Angular JS is called $scope.messages = []; In my template, I use ng-repeat: <div ng-repeat="item in messages"></div> When attempting to add a new element to the end of the array, I follow these ste ...

Guidelines for calculating the total value within a specific time frame

For my current project, I am using LocalStorage to store an array of dates and costs. When the code localStorage.getItem("todos"); is executed in the console, the output looks like this: "[{"due":"28/10/2017","task":"80"},{"due":"06/10/2017","task":"15"}] ...

Implementing dynamic state updates in React when handling an array of objects

Utilizing axios.get to access my MongoDB, I receive an array of objects with database information. My goal is to store only the usernames of each user in state. Despite attempting to set the response (res.data.username) to my state, when checking my state ...

What is the best way to transfer information from a layout to its children within the app directory of Next.js?

One scenario I encounter frequently is the need for a button in a layout to toggle something within the components it contains. For instance, you might have a notifications button in a fixed layout that triggers a side panel to open in the main application ...

Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected. How can I fix the issue with the click event not working? The gets functi ...

Dealing with uncaught promise rejection while using the 'opn' npm package in Docker

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Exited with code 3 I encountered this error while trying to open links using a module within a Docker container. The code functioned fine on my local machine without D ...