Angular UI Router Reload Controller on Back Button Press

孤人 提交于 2019-12-04 06:24:00
Andrew Clavin

You should listen to the event for succesful page changes, $locationChangeSuccess. Checkout the docs for it https://docs.angularjs.org/api/ng/service/$location.

There is also a similar question answered on so here How to detect browser back button click event using angular?.

When that event fires you could put whatever logic you run on pageload that you need to run when the controller initializes.

Something like:

$rootScope.$on('$locationChangeSuccess', function() {
    $scope.searchDirectory()
});  

Or better setup like:

var searchDirectory = function () {
    $state.go('directory.search', {
        name: $scope.Model.Query.name,
        email: $scope.Model.Query.email
    }, { reload: true });

$scope.searchDirectory = searchDirectory;

$rootScope.$on('$locationChangeSuccess', function() {
    searchDirectory();
});  

Using the above, I was able to come up with a solution to my issue:

controller (code snippet):

...var searchDirectory = function (searchParams) {

            if (searchParams) {
                $scope.Model.Query.name = searchParams.name;
                $scope.Model.Query.email = searchParams.email;
            }

            $state.go('directory.search', {
                name: $scope.Model.Query.name,
                email: $scope.Model.Query.email,
            }, { reload: true });                   
        };...

       $rootScope.$on('$locationChangeSuccess', function () {
            //used $location.absUrl() to keep track of query string
            //could have used $location.path() if just interested in the portion of the route before query string params
            $rootScope.actualLocation = $location.absUrl(); 
        });

        $rootScope.$watch(function () { return $location.absUrl(); }, function (newLocation, oldLocation) {
            //event fires too often? 
            //before complex conditional was used the state was being changed too many times causing a saturation of my service
            if ($rootScope.actualLocation && $rootScope.actualLocation !== oldLocation && oldLocation !== newLocation) {
                searchDirectory($location.search());
            }
        });

        $scope.searchDirectory = searchDirectory;

 if ($state.params && Object.keys($state.params).length !== 0)
{..call to service getting data...}

This solution feels more like a traditional framework such as .net web forms where the dev has to perform certain actions based on the state of the page. I think it's worth the compromise of having readable query params in the URL.

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