Tomarto
Tomarto

Reputation: 2755

Redirect using AngularJS

I'm trying to redirect to another route using:

$location.path("/route");

But for some reason it is not working. I did an auto-complete widget using jQuery-UI and I'm calling a function from the scope once the user selects an option. I debugged it and it enters the function but it is never redirected to the other route. It only changes the route when I press a key.

I think it is kind of strange but I haven't figured out how to solve this. I used

window.location = "#/route";

and it works but I want to use the path() function.

Does anybody have any idea why this is happening?

Upvotes: 86

Views: 157360

Answers (6)

jfindley
jfindley

Reputation: 712

Check your routing method:

if your routing state is like this

 .state('app.register', {
    url: '/register',
    views: {
      'menuContent': {
        templateUrl: 'templates/register.html',
      }
    }
  }) 

then you should use

$location.path("/app/register");

Upvotes: 2

Renan Tomal Fernandes
Renan Tomal Fernandes

Reputation: 10978

With an example of the not-working code, it will be easy to answer this question, but with this information the best that I can think is that you are calling the $location.path outside of the AngularJS digest.

Try doing this on the directive scope.$apply(function() { $location.path("/route"); });

Upvotes: 109

Milan Jaric
Milan Jaric

Reputation: 5646

It is hard to say without knowing your code. My best guess is that the onchange event is not firing when you change your textbox value from JavaScript code.

There are two ways for this to work; the first is to call onchange by yourself, and the second is to wait for the textbox to lose focus.

Check this question; same issue, different framework.

Upvotes: 0

Raulucco
Raulucco

Reputation: 3426

If you need to redirect out of your angular application use $window.location. That was my case; hopefully someone will find it useful.

Upvotes: 15

dpactri
dpactri

Reputation: 351

Assuming you're not using html5 routing, try $location.path("route"). This will redirect your browser to #/route which might be what you want.

Upvotes: 20

Stepan Suvorov
Stepan Suvorov

Reputation: 26176

Don't forget to inject $location into controller.

Upvotes: 81

Related Questions