Is it possible to utilize a ternary operator in AngularJS beyond just the class attribute?

Struggling with handling null values while looping through a JSON object using AngularJS.

I am still learning the ropes of Angular.

<a href="#" data-mycustom="{{product.related}}">...</a>

If the 'related' property is null:

{
    "related":null
}

I aim to substitute it with "-1":

<a href="#" data-mycustom="-1">...</a>

Attempted using a ternary operator but it fails to evaluate correctly and just displays as plain text.

Answer №1

To add a custom attribute after evaluating an interpolation directive, you can simply use ng-attr.

Example:

<img src="#" ng-attr-data-custom="{{user.profile || 'default' }}">...</img>

Answer №2

To provide a comprehensive answer, here is the solution to the original poster's query about using a ternary operator in a directive:

Make sure to enclose the entire ternary statement within {{}}, not just the variable. For instance, instead of this

<a href="#" data-mycustom="{{product.related}} ? product.related : '-1'">...</a>

it should be written as

<a href="#" data-mycustom="{{product.related ? product.related : '-1'}}">...</a>

Otherwise, Angular will not interpret it correctly -- you will end up with the value of product.related followed by the literal string ? product.related : '-1'.

Answer №3

Utilize the or operator in your code using the provided example:

<a href="#" data-mycustom="{{product.related || -1}}">...</a>

Answer №4

Simply utilize this

<a href="#" ng-attr-data-custom="{{product.related || '-1' }}">...</a>

This is akin to saying "attempt to utilize product.related if it's available. If not, use -1 instead"

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

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

What is the reason behind JavaScript libraries opting for a structure of [{ }] when using JSON?

I have been experimenting with various Javascript libraries, and I've noticed that many of them require input in the format: [{"foo": "bar", "12": "true"}] As stated on json.org: Therefore, we are sending an object within an array. With this observ ...

Oops! An uncaught exception error occurred because the primordials were not defined

I used npm to install the package called aws-s3-zipper, but now I am encountering an error. This is the code snippet causing the issue: AWS = require("aws-sdk"); var S3Zipper = require("aws-s3-zipper"); function zipFolderOnS3() { var zipper = new S3 ...

Mongodb: Search for IDs within a nested array field

My MongoDB data structure includes user profiles with friend request information. Here's an example: { _id: "someId", profile: { username: "oliv", friendRequests: [ { fromUserId: "anId", accepted: false, created: " ...

Is it possible for the Vue.js application to show the component right where the cursor is located in the textarea?

I am looking to create a Vue.js component with the following capabilities: As the user types in the textarea, I want the component to display recommended words. For instance, if the user types the letter s, I want a dropdown list to appear with words ...

What could be causing the issue of being unable to connect to the NodeJS express server from any network?

Imagine having a web server running on port 3001 with the IP address 23.512.531.56 (obviously not a real one) and then switching to another network, like your neighbor's. Now, when you try entering 23.512.531.56:3001 in Chrome, why doesn't the se ...

What to do when encountering a 404 Error with `meta.json` in a Next.js Application

Hello fellow developers, I'm currently facing a challenge with my Next.js application. Upon running it, the terminal keeps throwing a meta.json 404 error, and I'm stuck on how to resolve it. Here are some key points for context: The Next.js app ...

Exploring the functionalities of ng-value and ng-model in text input form fields

As I create a form to update information in a database, everything seems to be functioning properly. The selected data is being retrieved correctly; however, it is not displaying in the text inputs on the webpage. Although the information appears correct ...

Can someone help me figure out this lengthy React error coming from Material UI?

Issues encountered:X ERROR in ./src/Pages/Crypto_transactions.js 184:35-43 The export 'default' (imported as 'DataGrid') could not be found in '@material-ui/data-grid' (potential exports include: DATA_GRID_PROPTYPES, DEFAULT ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

Issue with facebook button in reactJS where onClick() event is not being triggered

I'm facing an issue where my onClick handler is not working with the Facebook button from https://developers.facebook.com/docs/facebook-login/web/login-button/. However, it works fine with a regular div element. Any thoughts on why the onClick event ...

calling requestAnimationFrame from within a freshly created instance

I'm encountering an issue with executing an animation. Specifically, this problem arises within var ob1 = function() {};. Once triggered, the animation runs for a brief period before I receive the error message Uncaught RangeError: Maximum call stack ...

Step-by-step guide on positioning an image to show at the bottom of a div

I am trying to create a div that covers 100% of the screen height, with a table at the top and white space below it for an image. However, when I add the image, it ends up directly under the table instead of at the bottom of the DIV. I have searched on G ...

Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code: [ { "id": 364, "siteName": "FX21 - PortA", }, { "id": 364, "siteName": "FX21 - PortB", }, { "id": 370, "siteName": "FX05 - ER", }, I'm tr ...

Steps for transforming 112889 (in mmddyy format) into 11/28/89 or 11/28/1989

Is there a way to convert the unformatted date 112889 (mmddyy) into a specific format like 11/28/89? console.log(new Date('112889')) // The output I'm getting is: Sat Jan 01 112889 00:00:00 GMT+0800 I've searched extensively on Google ...

Show the JSON data that was returned

I'm encountering a problem trying to access and display the returned object. Since it's cross-domain, I'm using jsonp, but I'm unable to retrieve the returned object for some reason. $(function(){ var API = "https://ratesjson.fxcm. ...

Modifying a JavaScript code with document.write(variable)

I am working with a Javascript function function setComparison(data) { var w= window.open('', 'comparison', 'width=600, height=400'); w.document.open(); w.document.write(getComparisonContent(data)); w.document ...

Executing a JavaScript function through C# code

Does anyone have a code snippet for calling a JavaScript function from C#? Here's the scenario: I have an ASP.NET page with an ASP button. When this button is clicked, I want to call a JavaScript function. For example: In my ASP.NET page, <but ...

Removing borders from textField in ReactJS can be achieved using a combination of CSS

Is there a way to remove the border from a TextField component? <Box display="flex" alignItems="center" border="1px solid #ccc" borderRadius="4px" paddingLeft="10px"> <Typography variant=&quo ...