Javascript ng-href 中的 Angularjs 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29890178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:15:04  来源:igfitidea点击:

Angularjs function in ng-href

javascriptangularjsmodel-view-controllerangularjs-ng-href

提问by user4773604

I want to call a function in ng-href and return the link from the function.

我想在 ng-href 中调用一个函数并从该函数返回链接。

When I click the function it sends page to that function in url. Like:

当我单击该函数时,它会将页面发送到 url 中的该函数。喜欢:

localhost/pageLink()

本地主机/页面链接()

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

How can i run the function and return correct link?

如何运行该函数并返回正确的链接?

回答by naeramarth7

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 mustdo! It watches the pagelinkmethod for changes and updates the hrefattribute.

对于任何抱怨这将在启动时执行代码的人:这正是它必须做的!它监视pagelink方法的更改并更新href属性。

The original questions was:

原来的问题是:

How can i run the function and return correct link?

如何运行该函数并返回正确的链接?

pagelink()should not handle routing but rather return a stringpointing to the target route. See the ngHref documentation.

pagelink()不应处理路由,而是返回指向目标路由的字符串。请参阅ngHref 文档

If you want to handle routing by yourself, you should rather use ngClick, not ngHref.

如果你想自己处理路由,你应该使用ngClick,而不是ngHref

回答by Scott Koland

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

假设pagelink()$rootScope,您将使用ng-click

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

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

你需要href=""这样浏览器会在鼠标悬停时改变光标。