AngularJS: Change hash and route without completely reloading controller

前端 未结 10 1218
鱼传尺愫
鱼传尺愫 2020-12-07 19:29

I have a controller, with a route like this:

#/articles/1234

I want to change the route without completely reloading the controller, so I can keep the positi

10条回答
  •  太阳男子
    2020-12-07 19:51

    You can do this without the $locationChange~ and HistoryState hacks using routes resolve promise option.

    Assuming you had an article route where that number is what changed you could do this;

    $routeProvider.when(
        '/article/:number',
        {
            templateUrl : 'partial.html',
            controller : 'ArticleCtrl',
            resolve : {
                load : ['$q', '$routeParams', function($q, $routeParams) {
                    var defer = $q.defer();
    
                    //number was specified in the previous route parameters, means we were already on the article page
                    if ($routeParams.number)
                        //so dont reload the view
                        defer.reject('');
                    //otherwise, the number argument was missing, we came to this location from another route, load the view
                    else
                        defer.resolve();
    
                    return defer.promise;
                }]
            }
        }
    );
    

提交回复
热议问题