如何将基于条件的href添加到<a> tag in AngularJs

时间:2017-08-02 11:19:00

标签: javascript jquery html 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

2 个答案:

答案 0 :(得分:2)

使用ng-if检查: -

<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>

答案 1 :(得分:1)

您可以在此处使用表达式: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>