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?
The ng-href directive overrides the original href attribute of an <a> element. The ng-href directive should be used instead of href if you have AngularJS code inside the href value. The ng-href directive makes sure the link is not broken even if the user clicks the link before AngularJS has evaluated the code.
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With