AngularJS - Get previous route when firing controller

孤街醉人 提交于 2019-12-05 16:08:31

I tried what ever I could, but it seems there is no straightforward way to get access to the previous route's path inside of the $routeProvider's resolve property.

Just for fun, I implemented a (ridiculously complex) solution with the following attributes:

  • It detects the previous route only if the /trash view is loaded (not for every route).
  • It doesn't have to know anything about the rest of the routes.
  • No extra configuration is needed when adding additional routes (this adds implementation complexity, but simplifies maintainance).

In words

Here is how it works in "plain" words:

In the resolve object, it registers a listener for the next $routeChangeSuccess event.
Once the event is captured, it unregisters the listener.
Once the listener is unregistered, it resolves a promise with value of the previous route's path. The object injected into the trashCtrl (from the resolve property) is a function, that returns the aforementioned promise.
The controller, receives that function, calls it to get the promise and waits for the promise to get resolved with the previous route's path.

Simple as pie !

Note: For the sake of "simplicity" I haven't taken into account the posibility of an error leading to $routeChangeError (instead of $routeChangeSuccess). One should probably take that into account and deregister the listeners, but even if you don't, there will be no harm - the listener will leave on until the $routeChangeSuccess is fired once.


The code

The controller:

app.controller('trashCtrl', function ($scope, prevRoutePromiseGetter) {
    prevRoutePromiseGetter().then(function (prevRoute) {
        $scope.prevRoute = prevRoute || 'nowhere';
    });
});

The resolve object:

resolve: {
    prevRoutePromiseGetter: function ($q, $rootScope) {
        var deferred = $q.defer();
        var dereg = $rootScope.$on('$routeChangeSuccess', 
            function(evt, next, prev) {
                dereg();
                deferred.resolve((prev.originalPath || '').substr(1));
            }
        );
        return function () {
            return deferred.promise;
        };
    }
}

See, also, this short demo.

You need to be using the $routeChangeStart and not the location change.

$rootScope.$on('$routeChangeStart', function(event, next, current) {

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