2

I want to make a redirection to another route and the page have to be refreshed and treated server side, so the $location.path(url) can't help me. I have tried window.location(url) but I have this error: window.location is not a function

My app.js:

    'use strict';
var app = angular.module('myApp', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider.when('/', {
        templateUrl: 'partials/index'});
    $routeProvider.when('/logout', {
        controller: 'logoutCtrl'});
    $routeProvider.otherwise({
        redirectTo: '/'});
    $locationProvider.html5Mode(true);
  }]);

my logoutCtrl:

function logoutCtrl($scope, $location){
    $apply(function() { 
        $location.path("/users/logout"); 
    });
}

The partials/index contains this link:

a(href='/logout') Logout

Now I'm going to show how I manage my routes server side with Express.js:

app.get('/', ctrl.index);
app.get('/partials/:name', ctrl.partials);
app.get('/users/logout', ctrl.logout);

exports.logout = function(req, res)
{
  console.log('logout');
  req.session.destroy(function(err){ // I destroy my session
   res.redirect('/'); // redirection to '/'
  });
}

Now when I click on "logout" nothing happen, I'm just seeing this route localhost:3000/logout in my bar but if I type localhost:3000/users/logout I have the result expected (session destroyed and redirection to '/' )

2 Answers 2

4

With an example of the not working code will be easy to answer this question, but with this > information the best that I can think is that you are calling the $location.path outside of > the angularjs digest.

Try doing this on the directive scope.$apply(function() {$location.path("/route");});"

-Renan Tomal Fernandes

Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't work for me. I'm going to add my code to my previous post :)
its $scope.$apply or scope.$apply
0

Just go with:

window.location.assign(url);

Alternatively:

window.location.replace(url);

which doesn't save the current page in browser session history.

2 Comments

This question has been asked in the context of AngularJS. It is never recommended to use non angular services in Angular e.g. $window is the Angular service. There are a number of reasons for that which might be irrelevant here.
Thanks for the lecture. Replace window with $window and the answer still works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.