Search code examples
angularjsangular-cookies

Setting a cookie in angularjs then routing to a new page


Angularjs version 1.3.15

I've gone ahead and set a cookie using $cookieStore.put on my page "A" and now wish to redirect the user to a new page "B" to utilize that cookie. My question is

How do I redirect a user to a known route defined in angular that results in a full page load which will read the cookie header and allow me access to my cookie?

This is the only method that I've found that works:

testControllers.controller('aController', ['$window', '$routeParams', '$cookieStore',
    function($window, $routeParams, $cookieStore) {
        $cookieStore.put('test', 1);

        if ($routeParams.bounce && $routeParams.bounce != '') {
            $window.location.href = '/#/' + $routeParams.bounce;
            $window.location.reload(true);
        } else {
            $window.location.href = '/#/';
            $window.location.reload(true);
        }
    }
]);

However it results in a double page load and is terrible. There has to be a better way.

Thanks in advance

Edit:

Page "B" is using a different controller which utilizes a directive, but I'm viewing the Resources tab in Chrome - which is how I see the cookie isn't seen by the browser yet. The directive I'm looking to view the cookie in:

testControllers
    .controller('menuDirective', ['$scope', '$cookieStore',
        function($scope, $cookieStore) {
            $scope.loggedin = false;

            if ($cookieStore.get('loggedin')) {
                $scope.loggedin = true;
            }
        }
    ])
    .directive('mymenu', function() {
        return {
            templateUrl: 'app/shared/menu/menuView.html'
        }
    });

Solution

  • I resolved this by having an if statement at the top of my login controller that checked for the existence of the cookie, and if it was there to do a location.path change. Then in my POST response to login which sets the login cookie simply do a window.location.reload(true); which will trigger the page refresh, populate the cookie in the browser, and allows the if statement to be hit.