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 '/' )

elghazal-a
  • 582
  • 1
  • 8
  • 15

2 Answers2

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

Community
  • 1
  • 1
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157
0

Just go with:

window.location.assign(url);

Alternatively:

window.location.replace(url);

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

Kugel
  • 19,354
  • 16
  • 71
  • 103
  • 3
    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. – Mohammad Umair Khan May 23 '14 at 06:03
  • Thanks for the lecture. Replace window with $window and the answer still works. – Kugel Oct 06 '15 at 13:46