最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I use a ternary operator with angularjs outside of the class attribute? - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jul 18, 2015 at 12:44 Pankaj Parkar 136k23 gold badges240 silver badges303 bronze badges asked Apr 22, 2015 at 19:46 user1447679user1447679 3,2707 gold badges38 silver badges76 bronze badges 3
  • Make sure your angular is the latest version. The ternary operator is a fairly new addition. – anon Commented Apr 22, 2015 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. – anon Commented Apr 22, 2015 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 Commented Apr 22, 2015 at 19:55
Add a ment  | 

4 Answers 4

Reset to default 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>

For the sake of pleteness, 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'.

use or operator. this code will help :

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

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"

发布评论

评论列表(0)

  1. 暂无评论