Change route parameters without updating view

三世轮回 提交于 2019-11-30 11:27:51

问题


I'm currently trying to figure out how to change the route parameters without reloading the entire page. For example, if I start at

http://www.example.com/#/page

but update a name to be 'George', to change the route to be:

http://www.example.com/#/page/george

If I already had http://www.example.com/#/page/:name routed.

Without reloading the location. Can one just set $routeParams.name = "George" ?

Edit: Alternatively, is there a way to update http://www.example.com/#/page?name=George without reloading or resetting the page?


回答1:


Ok, after a lot of searching. I answered my own question.

I've discovered finding anything on the angular documentation is incredibly impossible, but sometimes, once it's found, it changes how you were thinking about your problem.

I began here: http://docs.angularjs.org/api/ng.$location Which took me here: http://docs.angularjs.org/guide/dev_guide.services.$location Which took me to this question: AngularJS Paging with $location.path but no ngView reload

What I ended up doing: I added $location.search({name: 'George'}); To where I wanted to change the name (A $scope.$watch).

However, this will still reload the page, unless you do what is in that bottom StackOverflow link and add a parameter to the object you pass into $routeProvider.when. In my case, it looked like: $routeProvider.when('/page', {controller: 'MyCtrl', templateUrl:'path/to/template', reloadOnSearch:false}).

I hope this saves someone else a headache.




回答2:


I actually found a solution that I find a little more elegant for my application.

The $locationChangeSuccess event is a bit of a brute force approach, but I found that checking the path allows us to avoid page reloads when the route path template is unchanged, but reloads the page when switching to a different route template:

var lastRoute = $route.current;
$scope.$on('$locationChangeSuccess', function (event) {
    if (lastRoute.$$route.originalPath === $route.current.$$route.originalPath) {
        $route.current = lastRoute;
    }
});

Adding that code to a particular controller makes the reloading more intelligent.




回答3:


You can change the display of the page using ng-show and ng-hide, these transitions won't reload the page. But I think the problem you're trying to solve is you want to be able to bookmark the page, be able to press refresh and get the page you want.

I'd suggest implementing angular ui-router Which is great for switching between states without reloading the page. The only downfall is you have to change all your routes.

Check it out here theres a great demo.



来源:https://stackoverflow.com/questions/17981281/change-route-parameters-without-updating-view

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