Rowandish
Rowandish

Reputation: 2735

Angular JS cleanest way to conditionally append string to tag attribute

I have a very newbie question about angularJS:

I have two <a> tag very similar to show their href depends only if the variable foo is set:

if foo == null:

<a ng-href="#/bar/{{col.slug}}">{{col.title}}</a>

else

<a ng-href="#/{{foo}}/bar/{{col.slug}}">{{col.title}}</a>

As you can see the tags are pretty the same except for the foo variable appended at the beginning of the url.

I know there are commands like ng-show and ng-hide, ng-if or ternary operation.

How to make this operation in the cleanest way?

Thanks!

Upvotes: 1

Views: 635

Answers (2)

Brett
Brett

Reputation: 107

The less data that you send to the browser the better.

 <a ng-href="#/{{ !!foo ? foo + '/' : '/'}}bar/{{col.slug}}">{{col.title}}

Upvotes: 0

Ben Diamant
Ben Diamant

Reputation: 6206

You can condition your code:

<a ng-href="#/{{ foo != null ? foo + '/' : ''}}bar/{{col.slug}}">{{col.title}}</a>

Or you can use ngShow:

   <a ng-show="foo == null" ng-href="#/bar/{{col.slug}}">{{col.title}}</a>
   <a ng-show="foo != null" ng-href="#/{{foo}}/bar/{{col.slug}}">{{col.title}}</a>

I prefer inline condition, find it more redable

Upvotes: 4

Related Questions