Redirect using AngularJS

AngularjsRedirectLocation

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

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"); });

Solution 2 - Angularjs

Don't forget to inject $location into controller.

Solution 3 - Angularjs

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

Solution 4 - Angularjs

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

Solution 5 - Angularjs

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");

Solution 6 - Angularjs

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomartoView Question on Stackoverflow
Solution 1 - AngularjsRenan Tomal FernandesView Answer on Stackoverflow
Solution 2 - AngularjsStepan SuvorovView Answer on Stackoverflow
Solution 3 - AngularjsdpactriView Answer on Stackoverflow
Solution 4 - AngularjsRauluccoView Answer on Stackoverflow
Solution 5 - AngularjsjfindleyView Answer on Stackoverflow
Solution 6 - AngularjsMilan JaricView Answer on Stackoverflow