AngularJS - get the previous route when the managing controller

Angular insides puzzled me again.

I need to determine the previous route when loading a specific view.

This is how i did it

app.controller('TrashCtrl',function($scope,$rootScope){

    $rootScope.$on('$locationChangeSuccess',function(evt, absNewUrl, absOldUrl) {

        var hashIndex = absOldUrl.indexOf('#');

        var oldRoute = absOldUrl.substr(hashIndex + 2);

        console.log(oldRoute);

    });

});

Unfortunately, I have to call a view that matches this controller once before the logic starts working. At the first start of the controller, nothing is registered. In addition, after this initial loading, the application will register every routeChange, even if the loaded view does not work withTrashCtrl

I would like it:

  • When the view is loaded Trash(whose controller is located TrashCtrl), I need the previous route or an empty line if this is the first.
  • , Trash, .

?

Edit:

, . , . , , , Trash.

+4
2

, , , , $routeProvider resolve.

( ) :

  • /trash ( ).
  • .
  • ( , ).

"" :

resolve $routeChangeSuccess.
, .
, . , trashCtrl ( resolve), , .
, , , , .

!

< > : "" , $routeChangeError ( $routeChangeSuccess). , , , - , $routeChangeSuccess . >


:

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

resolve:

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;
        };
    }
}

. .

+7

$routeChangeStart, .

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

});
-1

Source: https://habr.com/ru/post/1542185/


All Articles