0

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>
Niro
  • 314
  • 1
  • 4
  • 25
  • 1
    Instead of using the `href` attribute, use angular's `ngHref` like this: `` – Alon Eitan Dec 27 '16 at 18:32
  • Possible duplicate of [Conditionally adding data-attribute in Angular directive template](http://stackoverflow.com/questions/22049824/conditionally-adding-data-attribute-in-angular-directive-template) – Walfrat Dec 27 '16 at 18:50
  • The anchor tag itself doesn't matter. It could be on any tag, with any property. – Niro Dec 27 '16 at 22:01
  • I'll edit the question with a better example – Niro Dec 27 '16 at 22:03
  • @NirD. There's no such thing as `ng-else` if the condition inside the `ngIf` evaluated as **true** then the element will be visible in the DOM, otherwise it is removed from the DOM (Unlike `ngHide` / `ngShow` that just make it visible or invisible, based on the condition). You can either use [ngInclude](https://docs.angularjs.org/api/ng/directive/ngInclude) or a directive and bind it to and `A` element, and avoid duplicate of the markup – Alon Eitan Dec 28 '16 at 20:52

1 Answers1

0

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.
Niro
  • 314
  • 1
  • 4
  • 25