2

I have a $scope.product variable. In my view I have this:

<a ng-href="/{{ gender }}/{{ section }}/{{ product.slug }}">{{ product.name }}</a>

If $scope.product.vendor exists, I want it to show

{{ product.vendor.name }} - {{ product.name}} ex: VendorName - ProductName

else, just show

{{ product.name }} ex: ProductName

How would I do this in the view? Or should this be done elsewhere?

P.S. that was a simplified version of my HTML. I already have a switch statement for another variable for the surrounding div, so this is what it actually looks like:

  <h3 ng-switch="locale">
    <a ng-href="/{{ locale }}/{{ gender }}/{{ section }}/{{ product.slug }}" ng-switch-when="cn">{{ product.name }}</a>
    <a ng-href="/{{ gender }}/{{ section }}/{{ product.slug }}" ng-switch-default>{{ product.name }}</a>
  </h3>
0

1 Answer 1

12

You can use ternary operators within the data-bindings:

<a ng-href="/{{ gender }}/{{ section }}/{{ product.slug }}">
    {{(product.vendor.length > 0) ? product.vendor.name + ' - ' + product.name : product.name}}
</a>
Sign up to request clarification or add additional context in comments.

3 Comments

This is a duplicate of a post I marked. It has a more complete answer. It is preferable to close vote as duplicate and give your answer on the original post if you think it can be done better. There's no need to keep answering the same question.
A good 60% of Q's on SO are some form of duplicates. I'm fine with this being deleted. I don't care for the rep, just helping the OP resolve. But i do agree that it's a dup and SO needs to be cleaned, I have marked as a dup.
@Asok might be worth a gander meta.stackoverflow.com/a/270420/829835

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.