简体   繁体   English

Angular - 从JavaScript重定向到路由

[英]Angular - Redirect to a Route from JavaScript

How do I properly redirect a user to a route in Angular in from JavaScript? 如何从JavaScript中正确地将用户重定向到Angular中的路由?

Most of the redirection that I'm doing is simply from clicking a link, and this works great. 我正在做的大多数重定向只是单击一个链接,这很有用。

<a href="#main">Main</a>

However, if I do something like this: 但是,如果我做这样的事情:

<button class="btn btn-default" ng-click="performLogin()">Login</button>

$scope.performExternalLogin = function () {
    DoSomeAuthenticationStuff();
    window.location.href = "/#main";
}

This works the first time, but when the user does it a second time, I get an exception from Angular. 这是第一次使用,但是当用户第二次执行时,我从Angular得到一个例外。 I suspect that there's a better way to redirect to a route, but my Googling skills have not come through for me. 我怀疑有一种更好的方法可以重定向到一条路线,但我的谷歌搜索技能还没有通过。 I'd appreciate any help. 我很感激任何帮助。

Here's the exception: Unhandled exception at line 112, column 381 in http://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js 以下是例外: http ://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js第112行第381行的未处理异常

0x800a139e - JavaScript runtime error: [$rootScope:infdig] http://errors.angularjs.org/1.2.18/ $rootScope/infdig?p0=10&p1=%5B%5B%22fn 0x800a139e - JavaScript运行时错误:[$ rootScope:infdig] http://errors.angularjs.org/1.2.18/ $ rootScope / infdig?p0 = 10&p1 =%5B%5B%22fn

In Angular you should use the $location service to interract with the window's location: 在Angular中,您应该使用$location服务来交互窗口的位置:

$scope.performExternalLogin = function () {
    DoSomeAuthenticationStuff();
    $location.path('/main');   // Will redirect to `#/main`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM