Arun
Arun

Reputation: 1472

How to add conditional based href to a <a> tag in AngularJs

I have created a menu list, some menus having url and some have not. In case of a menu having url then only the href attribute shown otherwise only tag. I checked like below but it came href="#" in case of menu.Url empty.

<nav class="pushmenu pushmenu-left">
    <ul class="main-navigation">
        @* Here we will load only top level menu *@
        <li class="hidepush" ng-repeat="menu in menus| filter:{ParentID : null} : true">
            <a ng-attr-href="{{#{{ menu.URL }} || ''}}"><span class="{{ menu.css }}"></span> {{menu.Name}}</a>
        </li>
    </ul>
</nav>

Can anyone help. Thanks

Upvotes: 1

Views: 2407

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

Do it with ng-if check:-

<nav class="pushmenu pushmenu-left">
    <ul class="main-navigation">
        @* Here we will load only top level menu *@
        <li class="hidepush" ng-repeat="menu in menus| filter:{ParentID : null} : true">
            <a ng-if="!menu.URL"><span class="{{ menu.css }}"></span> {{menu.Name}}</a>
            <a ng-if="menu.URL" ng-attr-href="{{#{{ menu.URL }} || ''}}"><span class="{{ menu.css }}"></span> {{menu.Name}}</a>
        </li>
    </ul>
</nav>

Upvotes: 2

atiq1589
atiq1589

Reputation: 2327

You can use expression here like: variable ? true: false

<nav class="pushmenu pushmenu-left">
  <ul class="main-navigation">
    @* Here we will load only top level menu *@
    <li class="hidepush" ng-repeat="menu in menus| filter:{ParentID : null} : true">
        <a ng-attr-href="{{ menu.URL ? '#' + menu.URL : ''}}"><span class="{{ menu.css }}"></span> {{menu.Name}}</a>
    </li>
  </ul>
</nav>

Upvotes: 1

Related Questions