Doug Johnson
Doug Johnson

Reputation: 560

Angular - Redirect to a Route from JavaScript

How do I properly redirect a user to a route in Angular in from JavaScript?

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. 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

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

Upvotes: 3

Views: 545

Answers (1)

gkalpak
gkalpak

Reputation: 48211

In Angular you should use the $location service to interract with the window's location:

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

Upvotes: 4

Related Questions