Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs function in ng-href

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?

like image 661
user4773604 Avatar asked Apr 27 '15 07:04

user4773604


People also ask

How do I bind a href in AngularJS?

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.

Between which tags can an AngularJS source file be added to an HTML page?

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.

What is HTML href?

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!


2 Answers

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.

like image 27
Scott Koland Avatar answered Oct 17 '22 18:10

Scott Koland


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.

like image 158
naeramarth7 Avatar answered Oct 17 '22 17:10

naeramarth7