4

I'm trying to trigger angularJS routing inside of a function in controller, but it throws back "Uncaught TypeError: Cannot read property 'path' of undefined". Can't really see where I missed $location injection, guess it's 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'm using 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');

}])

1 Answer 1

6

Look at this code:

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

Unless you invoke this function like this gameLost($location) (which I doubt) $location is going to end up as undefined in local function scope, overwriting $location service from parent closure scope.

So I think all you need to do is to remove $location paremeter from gameLost function definition:

function gameLost() {
        var check = false;
        $location.path('/game-over');
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that definitely helped to get rid of error. Passing $location as function argument where the function is invoked does the same thing. Routing, however, doesn't happen. I would be grateful if you or anyone has any idea about it.
i got this "localhost:8000/#!/game-over" why this -> '/#!/' ??
@Benyamin If you are not using history mode ($locationProvider.html5Mode(true)) then the fallback is going to be hash mode # or #!. docs.angularjs.org/guide/$location

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.