Passing object between views (flash message)

All we need is an easy explanation of the problem, so here it is.

What is the best way to pass message in the below scenario.

In the success scenario of $scope.p.$save, the result contains a message (res.message), which I like to display in the next view ($location.path("/test/"+res.reply.Id)). Without AngularJS, I may pass it in the url or save it in session cookies. But, I guess there might be a better way in AngularJS as there is no browser redirect and the state should be available. What is the best way to achieve this?

Setting it in rootScope shows it while I use browser back button, and the scope of the message should only for the first navigation to the new view.

function NewCtrl(Phone, $location, $rootScope, $scope) {
    $scope.p = new Phone();
    $scope.save = function () {
        $scope.p.$save(
            {},
            function (res) {
                $rootScope.message = res.message **//<-- this will cause message still set when using browser back button, etc**
                $location.path("/test/"+res.reply.Id); **//<-- Req: needs to pass the message to next view**
            }, function (res) {
            //TODO
            }
        );
    };
}
....
PhoneApp.factory('Phone', function ($resource) {
    return $resource('/api/test/:_id')
});

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You could use a service which displays the flash on $routeChangeSuccess.

Each time you set a flash message, add it to a queue, and when the route changes take the first item off the queue and set it to the current message.

Here’s a demo:

http://plnkr.co/edit/3n8m1X?p=preview

Method 2

I was looking to implement similar functionality, but actually wanted more of a growl style message.

I’ve updated the excellent plinkr code that Andy provided above to include a ‘pop’ method that leverages the toastr growl-style notification library.

My update also lets you to specify the notification type (info, warning, success, error) and title.

The ‘pop’ method skips adding the message to the queue, and instead pops it up on the screen immediately. The set/get functionality from Andy’s previous plinkr remains mostly unchanged.

You can find my update here: http://plnkr.co/edit/MY2SXG?p=preview

Method 3

I don’t believe there’s a way to do this default to AngularJS. Your best bet would just be passing the message (encoded) through a query string.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply