Casting hyperlink behavior in AngularJS

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

  • if a certain condition is present (for example, if a certain cookie has the value x), clicking on the hyperlink should open a modal window;

  • if this condition is not met (for example, if the cookie is set to y), the hyperlink should act in the usual way and open the link in a new tab.

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 this behavior. If I leave both the ng-href and ngclick , then ng-href will insert the url and each click will open the page in a new tab. If I remove the ng-href directive, then the only way to open the link in another tab is through javascript, but this will prevent most browsers. I couldn’t come up with a way to make ng-href conditional (for example, the record <a ng-href="myCondition === true ? {{article.url}} : '#'"> does not work).

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

+7
angularjs hyperlink angularjs-ng-click
source share
3 answers

It 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> 
+11
source share

Here is a slightly 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); }; 
+2
source share

Here is what I came up with. It looks ugly, so if you have the best deals, they are very welcome:

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

  <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 a checkCookies() function that looks at the value of a particular cookie.

+1
source share

All Articles