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?

1
  • ng-href="{{ pagelink() }}" Commented Apr 20, 2018 at 8:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I get this error: "Error: $rootScope:infdig Infinite $digest Loop" when calling function that returns url. Why is this?
All this will do is call pagelink() in your controller when the page loads. Using ng-click without the interpolation should do the trick.
@ScottKoland The problem of using ng-click is you lose the abilities of <a> like target="_blank". Open a webpage in new tab is a suffer in javascript.
I find I need to add the attribute target="_self" for the link to work when you click it (and not just update the URL)
@Elio interpolation is totally legit here. See the documentation for the ngHref attribute: docs.angularjs.org/api/ng/directive/ngHref
|
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.

1 Comment

cannot open a webpage in new tab

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.