使用 AngularJS 重定向

我试图重定向到另一条路线,使用:

$location.path("/route");

但出于某种原因,它没有起作用。我使用 jQuery-UI 做了一个自动完成的小部件,一旦用户选择了一个选项,我就从作用域调用一个函数。我调试了它,它进入函数,但它从来没有被重定向到其他路由。只有我按下一个键,它才会改变路线。

我觉得这有点奇怪,但我还没想出怎么解决这个问题

window.location = "#/route";

但是我想使用 path()函数。

有人知道为什么会这样吗?

157208 次浏览

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

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

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.

Don't forget to inject $location into controller.

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

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