我如何让 ui-router 转到外部链接,例如 google.com? [英] How would I have ui-router go to an external link, such as google.com?
问题描述
例如:
$stateProvider
.state('external', {
url: 'http://www.google.com',
})
url 假设这是一个内部状态.我希望它像 href 或类似的东西.
url assumes that this is an internal state. I want it to be like href or something to that effect.
我有一个将从 ui-routes 构建的导航结构,我需要一个链接来转到外部链接.不一定只是谷歌,那只是一个例子.
I have a navigation structure that will build from the ui-routes and I have a need for a link to go to an external link. Not necessarily just google, that's only an example.
不是在链接中或作为 $state.href('http://www.google.com') 寻找它.在路由配置中声明性地需要它.
Not looking for it in a link or as $state.href('http://www.google.com'). Need it declaratively in the routes config.
推荐答案
Angular-ui-router 不支持外部 URL,您需要使用 $location.url()
或$window.open()
Angular-ui-router doesn't support external URL, you need redirect the user using either $location.url()
or $window.open()
我建议您使用 $window.open('http://www.google.com', '_self')
它将在同一页面上打开 URL.
I would suggest you to use $window.open('http://www.google.com', '_self')
which will open URL on the same page.
更新
您也可以通过添加参数external
来自定义ui-router
,它可以是true
/false
.
You can also customize ui-router
by adding parameter external
, it can be true
/false
.
$stateProvider
.state('external', {
url: 'http://www.google.com',
external: true
})
然后在您的状态中配置 $stateChangeStart
&在那里处理重定向部分.
Then configure $stateChangeStart
in your state & handle redirection part there.
运行块
myapp.run(function($rootScope, $window) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
if (toState.external) {
event.preventDefault();
$window.open(toState.url, '_self');
}
});
})
注意:在新窗口中打开 Plunkr 以使其正常工作,因为 google 由于某些安全原因无法在 iFrame 中打开.
Note: Open Plunkr in a new window in order to make it working, because google doesn't get open in iFrame due to some security reason.
这篇关于我如何让 ui-router 转到外部链接,例如 google.com?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!