Angularjs routing: Unable to read property "path" undefined

I am trying to call angular routing inside a function in the controller, but it throws out "Uncaught TypeError: cannot read the path" of the property "undefined". I can not understand where I missed the injection in $ location, suppose this is the reason.

var gameApp = angular.module('gameApp', ['ngRoute']);

gameApp.config(function($routeProvider, $locationProvider, $provide) {
  $locationProvider.html5Mode(true);
  $routeProvider

  // route for the home page
  .when('/', {
    templateUrl : 'home.html',
    controller  : 'mainController'
  })

  // route for the game page
  .when('/game', {
    templateUrl : 'game.html',
    controller  : 'gameController'
  })

  // route for the game over page
  .when('/game-over', {
    templateUrl : 'game-over.html',
    controller  : 'mainController'
  })

  // default
  .otherwise({
    redirectTo: '/'
  });
});

And part of my game controller when I use a router

gameApp.controller('gameController', ['$scope', '$location', function($scope, $location){
    function gameLost($location){
        var check = false;
        console.log ('You lose! Your score is ')
        $location.path('/game-over');

}])

+4
source share
1 answer

Take a look at this code:

function gameLost($location) {
        var check = false;
        console.log ('You lose! Your score is ')
        $location.path('/game-over');
}

If you do not call this function like this gameLost($location)(which I doubt) $locationwill end as undefined in the scope of the local function, overwriting the $locationservice from the scope of the parent's closure.

, , $location gameLost:

function gameLost() {
        var check = false;
        $location.path('/game-over');
}
+6

All Articles