Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I redirect from an AngularJS controller to an Express route?

I'm using the boilerplate stack from MEAN.io and finding it quite a good starting point, however I'm having trouble mixing the different routing commands. My app is going to have a simple signin page which is public, everything else is hidden behind that. I can check if the user is authenticated no problem, but I cannot for the life of me get Angular to load the signin page from the server. I already have a signin button on my html page that calls the correct route no problem at all, I just can't do the same thing from code.

The $location.path('/signin'); code doesn't call the server because it leaves the hash in the path

My Angular controller

angular.module('tms.tweets').controller('TweetsController', ['$scope', '$routeParams',
'$location', '$resource', 'Global', 'Tweets', function ($scope, $routeParams, $location,
$resource, Global, Tweets) {
$scope.global = Global;

$scope.find = function() {

    if(Global.authenticated){

        console.log(Global.authenticated);

        Tweets.query(function(tweets) {
            console.log("Tweets at Angular Controller: " + tweets.length);

            $scope.tweets = tweets;
        });
    }
    else{
        console.log("Unauthorized");

        $location.path('/signin');
    }

};
}]);
like image 804
Mark Avatar asked Jan 03 '14 09:01

Mark


2 Answers

Found the answer to my redirect issue, I swapped $location.path for

$window.location.href = '/signin';
like image 102
Mark Avatar answered Oct 19 '22 11:10

Mark


For my purposes calling $window.location.href = '/newpath'; from inside my controller was not working.

I've been using the following function if I need to reload within the controller:

    $scope.changeRoute = function(url, forceReload) {
        $scope = $scope || angular.element(document).scope();
        if(forceReload || $scope.$$phase) { // that's right TWO dollar signs: $$phase
            window.location = url;
        } else {
            $location.path(url);
            $scope.$apply();
        }
    };

Then you would call it like this:

    $scope.changeRoute('#/newpath');

I will say though that doing this should be avoided, and that adding a run phase to your app's configuration phase should be preferred. You can read more about adding a run phase to your app configuration here: http://www.angularjshub.com/examples/modules/configurationrunphases/

like image 24
DrewT Avatar answered Oct 19 '22 12:10

DrewT