问题描述
我试图触发angularJS在控制器中的函数中的路由,但它抛回未捕获类型错误:无法读取属性未定义的'路径'。真的不能看到我错过了$位置注射,猜测它的原因。
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');
}])
推荐答案
看这code:
function gameLost($location) {
var check = false;
console.log ('You lose! Your score is ')
$location.path('/game-over');
}
除非你调用这样这个功能 gameLost($位置)
(我怀疑) $位置
是去最终收在局部函数范围为未定义,从父封闭范围覆盖 $位置
服务。
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.
所以,我认为,所有你需要做的就是删除 $位置
paremeter从 gameLost
函数定义:
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');
}
这篇关于Angularjs路由:无法读取的未定义的属性“路径”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!