Reputation: 893
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');
}])
Upvotes: 4
Views: 17051
Reputation: 193261
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');
}
Upvotes: 6