2

I'm looping through a json object with AngularJS, and having trouble dealing with nulls.

I'm new to Angular.

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

In the event of related being null:

{
    "related":null
}

I want to put a "-1" in its place:

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

Tried ternary operator but it isn't evaluating... it's just displaying it as plain text.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
user1447679
  • 3,076
  • 7
  • 32
  • 69
  • Make sure your angular is the latest version. The ternary operator is a fairly new addition. – Nic Apr 22 '15 at 19:47
  • 2
    Well I'm stumped. There are several alternative syntaxes, like `{true: a, false: b}[condition]`, which I've tried and seem to work when ternary doesn't. You'd use that like any other angular statement. – Nic Apr 22 '15 at 19:49
  • Oh.. my.. gosh. I figured out what I was doing wrong. Tenary works fine, if I put it all inside the curly brackets. – user1447679 Apr 22 '15 at 19:55

4 Answers4

3

Simply you could use ng-attr to add custom attribute after evaluation of {{}} interpolation directive

Markup

<a href="#" ng-attr-data-mycustom="{{product.related || '-1' }}">...</a>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • 1
    I actually figured out what I was doing wrong, and boy do I feel dumb... However, this method is cleaner/shorter, so thank you. Will accept as soon as it lets me. – user1447679 Apr 22 '15 at 19:55
2

For the sake of completeness, this is the answer the OP's original question ("how do you use a ternary in a directive"):

Add {{}} around the entire ternary statement, not just the variable. For example, this

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

should be

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

Otherwise, Angular won't parse it -- you'll get the value of product.related, followed by the literal text ? product.related : '-1'.

Nic
  • 6,211
  • 10
  • 46
  • 69
  • I actually had the brackets around the just {{product.related}} instead of the whole tenary, so I was just half stupid :) – user1447679 Apr 23 '15 at 00:59
  • @user1447679 There! Fixed. – Nic Apr 23 '15 at 01:00
  • While the other answers are helpful, I think this answer should really be marked as the correct answer since it specifically talks about the ternary operator – shafeen Mar 28 '17 at 15:06
0

use or operator. this code will help :

<a href="#" data-mycustom="{{product.related || -1}}">...</a>
Mukund Kumar
  • 21,413
  • 18
  • 59
  • 79
0

Just use this

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

It is something like "try to use product.related if it exists. if it doesnt, use -1 insted"

Felipe Skinner
  • 16,246
  • 2
  • 25
  • 30