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

triggers an unexpected error in console.log

I need help with the following code: function printName(obj) { console.log(obj.name); } printName({ name: "myName" }); (function displayError(errorMsg){ console.log(errorMsg); })("Error"); However, when I try to run this code, I am encountering a T ...

Setting up Babel to effectively function across multiple directories

I've been utilizing Babel for some time now and it effectively transforms my ES Next code to the dist directory using this command: babel src --out-dir dist --source-maps --copy-files Up until now, all my JavaScript code has been stored in the src fo ...

What is the best way to capture the output of a script from an external website using Javascript when it is returning simple text?

Recently, I decided to incorporate an external script into my project. The script in question is as follows: <script type="application/javascript" src="https://api.ipify.org"> </script> This script is designed to provide the client's IP ...

Adding div elements using checkbox switch

In this code snippet, my aim is to display costs based on checkbox selection and generate corresponding totals in the bottom row when the checkboxes are toggled. The goal is to allow users to choose relevant items and have the total cost calculated accordi ...

Exploring the integration of ng-csv with Firebase data in an AngularJS project

Seeking assistance with ng-csv functionality to enable users to download a .csv file by clicking a button. The data is stored in Firebase, and I have a function that retrieves the necessary information as an array. However, it seems that upon button click, ...

Is the presence of an excessive number of arguments in the object that includes functions an instance

In my program, I have implemented a feature where the user can provide an array to determine which functions are executed in a loop. However, managing the list of variables that need to be passed into each function has become challenging as the list keeps ...

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Exploring the concept of promises in node.js for recursive functions

I'm attempting to use recursive calls in order to fetch data from redis, halting and returning when the members return null. My data is inserted as shown below: SADD parents.<name> <parent1> <parent2> SADD parents.<parent1> & ...

What methods can be used to troubleshoot an issue of an AngularJS function not being called

I am facing an issue with a dynamic table I have created. The rows and action buttons are generated dynamically when the user clicks on the Devices accordion. However, there seems to be a problem with the function expandCollapseCurrent(). Whenever the use ...

Can anyone explain why I am having trouble loading JavaScript files into a different HTML file?

Currently, I am developing an electron application. In my index.html file, I have successfully loaded JavaScript files in the head tag and can access the JS functions without any problems. Now, I have created a separate browser window with another HTML fi ...

Positioning the filters in jQuery Datatables

I'm currently working with jQuery datatables and I'm attempting to align the filter/search box on the same row as the header of the container holding the datatable. Attached is a screenshot for reference: https://i.stack.imgur.com/nzbIl.png He ...

What is the best way to access the inner html of every cell within a table row that I have selected?

I want to implement a feature on my website where users can click a "save" button on a specific row in a table and save the entire row's innerHtml onto another page as their favorite hiking trails. I've been trying to achieve this by adding clic ...

Use Javascript to display an image based on the date, otherwise hide the div

I'm looking to implement an image change on specific dates (not days of the week, but actual calendar dates like August 18th, August 25th, September 3rd, etc). Here's the div I'm working with: <div id="matchday"> <img id="home ...

How can the 'Read more' feature be modified to impact multiple boxes? (Using jQuery, JS, and CSS)

I am trying to add a 'Read more' feature on my friend's website. I was able to achieve the desired effect, but when I tried to adjust the alignment of the box, it affected the 'Read more' feature. Original design: https://codepen. ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...

Using data from an API, I am implementing JavaScript validation for my dropdown select menu

Using an API, I am able to access information about the city's subway stations through a select option. Currently, I can only display details about one station (Balard). However, I would like to be able to display information about other stations tha ...

How can I store a value or text to track view counts or a counter efficiently?

Recently, I've been trying to implement a view counter on my website, similar to what you see on YouTube. Currently, the number of views stands at 23. I managed to find some code that allows me to increment the view count every time I click on an imag ...

Flask fails to recognize JSON data when transmitted from Nodejs

I am encountering an issue when trying to send JSON data from Node to Flask. I am having trouble reading the data in Flask as expected. Despite attempting to print request.data in Flask, no output is being displayed. Additionally, when I tried printing req ...

Issue with Sequential Drop Down List Functionality in ASP.Net MVC View Page

I am currently in the process of migrating code from one project to another. Although the code works fine in the original project, it is not functioning properly in the new one. I’m uncertain if something was overlooked on my end. Within this code, ther ...

Deleting table rows after an object has been removed in AngularJSNote: Using

My AngularJS application retrieves a list of JSON objects and displays them in a table. Each row in the table includes a "Delete" button that triggers an ng-click method: <td><a ng-click="testButton()" class="btn btn-danger btn-mini">Delete&l ...