Making behavior of hyperlinks conditional in AngularJS
Asked Answered
C

3

7

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?

Concordat answered 8/2, 2015 at 18:24 Comment(2)
Seems like you conditionally need to include or remove the target attribute. Maybe have a look here? #23584701Verde
handle the logic inside controller whether to redirect or open modal popupLaclos
E
11

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>
Edessa answered 12/7, 2015 at 20:9 Comment(0)
B
2

Here is a bit different approach that worked for me, didn't use ng-href at all:

HTML:

<a ng-click="myFunc()">{{article.title}}</a>

Controller:

$scope.myFunc = function() {
  if (myCondition){
    window.open($scope.article.url,'_self',false);
  }
  window.open("/#/",'_self',false);
};
Blowhole answered 21/4, 2016 at 9:21 Comment(0)
C
1

Here is what I came up with. It looks kind of ugly, so if you have better suggestions, they are very welcome:

I wrote two separate anchor tags with different behaviors and made Angular choose between them depending on whether or not the necessary condition is met:

      <a href="#" ng-if="checkCookies() === 'show popup'" ng-click="openArticle(article)">
        {{$parent.article.title}}
      </a>

      <a ng-href="{{$parent.article.url}}" target="_blank" ng-if="checkCookies() === 'no popup'">
        {{$parent.article.title}}
      </a>

And in the javascript file, I wrote the checkCookies() function that looks up the value of the particular cookie.

Concordat answered 8/2, 2015 at 18:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.