Change route parameters without updating view

﹥>﹥吖頭↗ 提交于 2019-11-30 01:02:36
jbenowitz

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.

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.

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.

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