25

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?

Mauker
  • 11,237
  • 7
  • 58
  • 76
user4773604
  • 451
  • 3
  • 9
  • 16

2 Answers2

46

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.

naeramarth7
  • 6,030
  • 1
  • 22
  • 26
8

Assuming that pagelink() is at $rootScope, you would use ng-click:

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

You need the href="" so the browser will change the cursor on mouse over.

Scott Koland
  • 739
  • 9
  • 18