简体   繁体   中英

In angular, how can I use ng-if for the containing tag only without the trailing markup

Let's say I have two HTML elements with the same tag, but each with a different set of properties. How can I conditionally choose between them?

I have the following two tags:

<a ui-sref="root.one(::{param: value})">
<a target="_blank" href="{{::model}}">

I need to conditionally choose one of them, and add other markup until the closing tag. Can something like this work?

<a ng-if="::condition" ui-sref="root.one(::{param: value})">
<a ng-else target="_blank" href="{{::model}}">
  <div>
    more nodes
  </div>
</a>

At the end I figured this to be impossible, so I resorted to merging the A tags like this:

<a ng-attr-target="{{::!condition? '_blank' : undefined}}" href="{{::model}}" ng-attr-ui-sref="{{::(condition? 'root.one(::{param: value})' : '.')}}">

Remarks:

  1. When the condition is met, ng-attr-target expression is set to undefined so that the target attribute will not be inserted at all. Apparently, if you set it to _self it messes up angular routing
  2. When the condition is not met, ng-attr-ui-sref expression is set to some random undeclared ui-sref route - '.'. Usually you would just set it to undefined if you don't want the attribute to be inserted, but there's some bug in ui-sref or in angular, that results in some errors in the console so I had to resort to this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM