Building conditionals in AngularJS expressions using if-then-else syntax

Is there a way to incorporate the ternary-operator (if-then-else construction) in an angularjs expression? For example, I have a function $scope.isExists(item) that should return a boolean value. I would like to do something like this:

<div ng-repeater="item in items">
    <div>{{item.description}}</div>
    <div>{{isExists(item) ? 'available' : 'oh no, you don't have it'}}</div>
</div>

I understand that I can use a function that returns a string, but I am curious about the possibility of using if-then-else construction within an expression. Thank you.

Answer №1

Before version 1.1.5 of Angular, expressions did not support the ternary operator. However, you could emulate it using this syntax:

condition && (answer if true) || (answer if false)

For example, you could use something like this:

<div ng-repeater="item in items">
    <div>{{item.description}}</div>
    <div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>

UPDATE: Starting from Angular 1.1.5, ternary operators are now supported natively:

{{myVar === "two" ? "it's true" : "it's false"}}

Answer №2

If you're using version 1.1.5 or later, you have the option to utilize the ternary operator, as shown in this small example on Plunker (using version 1.1.5):

Just in case of any issues with plnkr.co in the future, here is the main code snippet from my example:

{{true?true:false}}

Answer №3

One way to utilize ng-show is by implementing it like this:


    <div ng-repeater="item in items">
        <div>{{item.description}}</div>
        <div ng-show="isAvailable(item)">In stock</div>
        <div ng-show="!isAvailable(item)">Sorry, out of stock</div>
    </div>

If the conditions are more intricate, you can make use of ng-switch statements such as this:


    <div ng-repeater="item in items">
        <div>{{item.description}}</div>
        <div ng-switch on="isAvailable(item)">
            <span ng-switch-when="true">Item Available</span>
            <span ng-switch-default>Sorry, out of stock</span>
        </div>
    </div>

Answer №4

Complete this task with just one line of code.

{{corretor.isAdministrador && 'YES' || 'NO'}}

If you want to use it in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Yes' || 'No'}}</td>

Answer №5

When looking for a way to determine if a key exists in an array using Angular, I came across this question. In AngularJS 1.4, the ternary operator functioned as follows:

{{ CONDITION ? TRUE : FALSE }}

Therefore, to check if the array key exists, I performed a simple JavaScript check.

Solution 1:

{{ array['key'] !== undefined ? array['key'] : 'n/a' }}

Solution 2:

{{ "key" in array ? array['key'] : 'n/a' }}

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

Implementing a delay of X seconds after a click event in JQuery: A step-by-step guide

Is there a way to delay the triggering of a click event after one has been recently triggered? I am facing an issue on my website where users can click multiple times on the "dropdown icon" and cause it to toggle the slide effect multiple times. What I wan ...

Testing Angular services by injecting dependencies

I'm currently working on test driven development for an angular service using Jasmine. However, I've encountered an issue with resolving the $resource dependency, which is causing a stumbling block at the beginning of my process. The specific er ...

Exploring the world of AngularJS: delving into $http requests, navigating

After facing challenges with using CORS and http authentication in AngularJS, I have learned an important lesson that I would like to share. Special thanks to igorzg for providing valuable assistance. The situation is as follows: You need to make a POST re ...

The function e.preventDefault() appears to be ineffective when applied to both the submit button and anchor tag within an

In my ASP.Net Core MVC App View <form> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4"> <div class="form-group"> <input type="text" class="form-contr ...

How can the node version be set globally in NVM?

While utilizing Node Version Manager, setting the node version to the latest one in the current directory can be done using nvm use node. But how can you specify a specific version to use? ...

Executing requests asynchronously in AngularJS in a sequential manner

I have a need to run 3 requests concurrently. Here is the current code I am using: for (var url in urls){ console.log('queued!'); $http.jsonp(url, {timeout: 10000}).then(function (response, status, headers, config) { if (resp ...

The default export (imported as 'Vue') could not be located within the 'vue' module in Vue 3 and Laravel

I'm currently in the process of building a project that combines Laravel 8 and Vue JS 3. I've set everything up, but whenever I try running `npm run watch`, I encounter an error message similar to the one below. Despite looking through various fo ...

Azure webhosting blocks the use of AJAX calls

There is a PHP script hosted on my Azure server that returns JSON when accessed through the browser. However, I am having trouble making an AJAX call to this script as none of my requests seem to go through. The issue remains unclear. You can see a failed ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

Attempting to utilize the JavascriptExecutor for button testing, however encountering an error message stating 'Unexpected keyword or identifier'

When I look at my code, I see this line: JavascriptExecutor js = (JavascriptExecutor) driver; A red line appears underneath it with the error message Unexpected keyword or identifier I attempted to resolve this by importing org.openqa.selenium.Javascrip ...

What happens to the content within a <textarea> element if it is not enclosed between the opening and closing tags?

Here's a puzzling situation - I've entered the word Hello. into a <textarea>, and while I can see it on my screen, it doesn't show up between the opening and closing <textarea> tags. It may seem like a simple issue, but I'v ...

Is it possible to utilize both body-parser and Formidable simultaneously?

I've been working on a problem for a few days now, but I'm having trouble understanding certain aspects of it. My website is built using NodeJS and ExpressJS, with form handling done through body-parser. var adName = req.body.adName; var adMess ...

What are the best practices for creating a contemporary website that functions effectively on IE7?

After creating several websites for my clients, I discovered that they are not functioning well in IE7. Unfortunately, there is still a small percentage of people using IE7. Can anyone suggest a super quick solution to fix this issue? Feel free to recomm ...

Having trouble passing parameters in a Node.js express POST request?

Here is the code snippet I am currently working with: const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); app.post('/rasp&apos ...

Database-Driven Ajax Information Display

I retrieved some data from the database and successfully displayed it after an ajax call. However, one of the variables contains array data that was saved using the implode function. The data looks like (a,b,c,d). The current display format is as follows: ...

Keeping an object in a multidimensional array based on its ID in Angular 4/Ionic 3 without removing it

Exploring a complex data structure: [{ propertyoutsideid: 1, items: [ {itemId: 1, something: 'something'}. {itemId: 2, something: 'something'}. {itemId: 3, something: 'something'}. ] },{ prope ...

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

Using JavaScript and HTML, create a click event that triggers a drop-down text

Can anyone help me with creating a dropdown feature using JavaScript, HTML, and CSS? I want to be able to click on the name of a project and have information about that project show up. Any suggestions on how I can achieve this? Thanks in advance! ...

Troubleshooting: Error in angular JavaScript due to minification: $injector:modulerr Module Error

After defining my angular code as shown below, I encountered an issue when trying to minify the javascript. The error message displayed was: $injector:modulerr Module Error. angular.module('myModule').controller('MyController', functio ...