Angularjs function in ng-href

user4773604 picture user4773604 · Apr 27, 2015 · Viewed 45.8k times · Source

I want to call a function in ng-href and return the link from the function.

When I click the function it sends page to that function in url. Like:

localhost/pageLink()

<a ng-href="pagelink()" >Link</a>

How can i run the function and return correct link?

Answer

naeramarth7 picture naeramarth7 · Apr 27, 2015

Interpolation might do the trick:

<a ng-href="{{pagelink()}}">Link</a>

Edit:

To anyone complaining, that this will execute the code at startup: That's exactly what it must do! It watches the pagelink method for changes and updates the href attribute.

The original questions was:

How can i run the function and return correct link?

pagelink() should not handle routing but rather return a string pointing to the target route. See the ngHref documentation.

If you want to handle routing by yourself, you should rather use ngClick, not ngHref.