Angular.js - Redirection not working

By : hamou92
Source: Stackoverflow.com
Question!

I have somes difficulties to understand the behavior of Angular.js routing

Here is my code

my app.js:

'use strict';

var app = angular.module('myApp', []).
  config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
    $routeProvider.when('/game/room', {templateUrl: 'roomGame', controller: roomCtrl});
    $routeProvider.otherwise({redirectTo: '/game/room'});
    $locationProvider.html5Mode(true);
  }]);

index.js where I define the routes server side:

app.get('/game', function (req, res)
{
  console.log("we are in /game");
  res.render("game/index", {
      user: req.session
  });
});
app.get('/game/roomGame', function (req, res)
{
  console.log("we are in /game/roomGame");
  res.render("game/roomGame";
});

index.jade:

div(ng-controller="indexCtrl")
    a(href='/') Quitter

    div(ng-view)

And there is an other file: roomGame.jade but it's not important to show you the source code.

Now I open my browser and enter : localhost:3000/game.

As expected I'm redirected to localhost:3000/game/room and it shows me the expected view.

But when I enter : localhost:3000/game/room or localhost:3000/game/foo it shows me "cannot GET /game/xxx"

I want to be redirected to /game and then to /game/room. How it is possible ?

By : hamou92


Answers

When you see the expected view, are you being redirected to http://localhost:3000/#/game/room? Note the #.

When you enter http://localhost:3000/game/room, this hits the express server, and not your Angular app, trying to match /game/room, hence the message you're seeing.

One idea is to go like this on your server:

app.get('/game/:what', function (req, res) {
    res.redirect('/#/game/'   req.params.what);
});

or more likely:

app.get('/game/*', function (req, res) {
    res.redirect('/#/game');
});

This will redirect things from express to a place where Angular can deal with them.

By : exclsr


This video can help you solving your question :)
By: admin