Making behavior of hyperlinks conditional in AngularJS

azangru picture azangru · Feb 8, 2015 · Viewed 11.4k times · Source

In an Angular app, I have a list of hyperlinks that need to have the following behavior:

  • if a certain condition is present (e.g. if a certain cookie has value x), a click on the hyperlink should open a modal window;

  • if this condition is not met (e.g. if the cookie has value y), the hyperlink should act in its usual manner and open the link in a new tab.

The hyperlinks are formatted as follows:

<a ng-href="{{article.url}}" target="_blank" ng-click="myFunction()">
  {{article.title}}
</a>

I am puzzled by how to implement such a behavior. If I leave both ng-href and ngclick directives, then ng-href will insert the url and every click will open a page in a new tab. If I remove the ng-href directive, then the only way to open a link in another tab will be through javascript, but this is prevented by most browsers. I couldn't think of a way to make ng-href conditional (for example, writing <a ng-href="myCondition === true ? {{article.url}} : '#'"> doesn't work).

Could you please suggest a way of how to implement such a functionality in Angular?

Answer

Sage picture Sage · Jul 12, 2015

This worked for me

<a ng-href='{{(element.url.indexOf("#")>-1) ? element.url : element.url + "client_id="}}{{credible.current_client_info.client_id}}'>{{element.title}}</a>