Angularjs function in ng-href

45,806

Solution 1

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.

Solution 2

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.

Share:
45,806
user4773604
Author by

user4773604

Updated on July 28, 2022

Comments

  • user4773604
    user4773604 almost 2 years

    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?