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?

isherwood
  • 58,414
  • 16
  • 114
  • 157
azangru
  • 2,644
  • 5
  • 34
  • 55
  • 1
    Seems like you conditionally need to include or remove the `target` attribute. Maybe have a look here? http://stackoverflow.com/questions/23584201/conditionally-add-target-blank-to-links-with-angular-js – Lukas S. Feb 08 '15 at 18:29
  • handle the logic inside controller whether to redirect or open modal popup – Pankaj Parkar Feb 08 '15 at 18:30

3 Answers3

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>
Sage
  • 4,769
  • 1
  • 21
  • 28
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);
};
Vali D
  • 511
  • 1
  • 6
  • 20
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.

azangru
  • 2,644
  • 5
  • 34
  • 55