Search code examples
javascriptangularjstoastr

Show Toastr message when redirecting page


I have a form which calls the below function on submit.

    function addToCart(form) {
        if (form.$valid) {
            shopFactory.addToCart(vm.model.ProductDetail).then(function () {
                toastr.success("Added to cart");
                $window.location = "shop/myCart";
            });
        }
    }

The function redirects to the page myCart, and a Toastr message displays.

My issue is that the toastr message disappears immediately as the message appears on the current page which the user is directed away from.

Is there a way to get the message to sustain through a redirect, or to simply appear on the next page?


Solution

  • Inside shop/myCart page controller, Write code inside, $stateChangeSucces (if using ui.router) or $routeChangeSuccess.Also check the previous route to enusre that toastr message displays only for this case.

    EXample:

    $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
        console.log("foo");
      });
    });