Javascript 如何使用 $route 和 $routeParams 更新 angular js 中的 url?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12797211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I update the url in angular js with $route and $routeParams?
提问by Mythriel
How can I redirect or update the url? I cannot find any good documentation regarding this. Basically, what I want to do is to change the $routeParams dynamically and update the url with the new value.
如何重定向或更新网址?我找不到任何关于此的好的文档。基本上,我想要做的是动态更改 $routeParams 并使用新值更新 url。
My code looks like this:
我的代码如下所示:
if ($routeParams.time) {
var url;
$routeParams.time = encodeURIComponent(value);
url = '/' + $routeParams.time + '/' + 'marketing/networks';
$location.path(url);
} else {
$routeParams.time = encodeURIComponent(value);
url = '/' + $routeParams.time + $location.path();
$location.path(url);
}
回答by Robert
After reading the comments to my answer, I think maybe is not the right answer for this case. Please, before using this solution, read the comments and other answers. I'm not using Angular anymore so I don't feel qualified for answering.
在阅读了对我的答案的评论后,我认为可能不是这种情况的正确答案。在使用此解决方案之前,请阅读评论和其他答案。我不再使用 Angular,所以我觉得没有资格回答。
I leave the original answer unmodified below:
我在下面保留原始答案不变:
You are changing the location properly but AngularJS it's not realizing that it changed. You can solve the problem using the method '$apply' of your scope like this:
您正在正确更改位置,但 AngularJS 没有意识到它已更改。您可以使用范围的“$apply”方法解决问题,如下所示:
$location.path( url );
$scope.$apply();
Or like this:
或者像这样:
$scope.$apply( $location.path( url ) );
See $apply documentation here http://docs.angularjs.org/api/ng.$rootScope.Scope
请参阅此处的 $apply 文档http://docs.angularjs.org/api/ng.$rootScope.Scope
回答by Tosh
You might want to try native browser object $window.location.href
instead, according to http://docs.angularjs.org/guide/dev_guide.services.$location(in Caveats
section).
$window.location.href
根据http://docs.angularjs.org/guide/dev_guide.services.$location(in Caveats
section) ,您可能想尝试使用本机浏览器对象。
回答by danday74
you should use https://angular-ui.github.io/
你应该使用https://angular-ui.github.io/
ui-router
用户界面路由器
when using this you can do ...
使用它时,您可以这样做...
state.go("route-name", {id:4});
state.go("路由名称", {id:4});
much better than the built in routing service
比内置的路由服务好得多
The most voted answer is worrying!
得票最多的答案令人担忧!