AngularJS - Best way to update $route parameter

时光毁灭记忆、已成空白 提交于 2019-12-03 10:44:53

Since angular 1.3 you can use $route.updateParams(newParams) to change route params.

Here is a quote from the angular docs...

$route.updateParams(newParams);

Causes $route service to update the current URL, replacing current route parameters with those specified in newParams. Provided property names that match the route's path segment definitions will be interpolated into the location's path, while remaining properties will be treated as query params.

Khanh TO

If it's possible, I would recommend you to use ui-router instead. It's more powerful than ngRoute in many aspects.

Essentially, this module has a higher level concept called state wrapping the underlying route which shields you from working directly with lower route level like route urls.

For a comparison: What is the difference between angular-route and angular-ui-router?

With ui-router, you can implement your code like this:

$stateProvider
  .state('user.chart', {
     url: '/user/:accountId/charts/:chartType',   
     controller: "ChartsController"   
  })
 .state('manager.chart', {
     url: '/manager/:accountId/charts/:chartType', 
     controller: "ChartsController"
  })
 .state('pathy.chart', {
     url: '/whatever/pathy/paththingy/charts/:chartType', 
     controller: "ChartsController"
  })

And you could just use this code to navigate between states:

$state.go('user.chart',{chartType:'newChart'},{inherit:true});

Documentation

The lack of this simple feature annoyed me, so I Implemented it and filed a PR on GitHub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!