Scipion
Scipion

Reputation: 11888

Angularjs Setting a condition on history.back()

I currently have the following directive:

ngModule.directive('backButton', ['$window',
    function ($window) {
        return {
            restrict: 'A',
            scope: {},
            templateUrl: null,
            link: function (scope, element) {
                scope.comingFromIndex = function () {
                    ...
                };

                scope.backToIndex = function() {
                    $window.history.back();
                };
            }
        };
    }
]);

and in my template I call the back function this way:

<a data-ng-click='backToIndex()' data-ng-hide='!comingFromIndex()'>Return To The Index</a>

The function comingFromIndex is currently not implemented because I am not sure how to do it. The page where this back button is can be reached from the index, and from other pages as well. In my case, I want this back button to be shown only when I am coming from the index. I am not sure what's the best way to do so, any suggestions ?

Upvotes: 1

Views: 1053

Answers (3)

Donal
Donal

Reputation: 32713

You would need to implement something like ui-router as your route provider.

It broadcasts state changes to the rootScope, you can pick up the state changes with something like the following:

$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
   //check the "from" parameter - it will contain the url of the previous page.
});

Upvotes: 1

Scipion
Scipion

Reputation: 11888

I found the answer there:

https://github.com/angular-ui/ui-router/issues/92

using: angular.module('sample') .run( [ '$rootScope', function ($rootScope) { $rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams) { $rootScope.$previousState = from; }); }]);

Upvotes: 0

NewDirection
NewDirection

Reputation: 114

Try as below code: (Reference)

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

Upvotes: 0

Related Questions