Search code examples
javascriptangularjsif-statementhrefangularjs-ng-href

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!


Solution

  • 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