javascript Angularjs 路由:无法读取未定义的属性“路径”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25929696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angularjs routing: Cannot read property 'path' of undefined
提问by vitalym
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.
我正在尝试在控制器中的函数内部触发 angularJS 路由,但它返回“未捕获的类型错误:无法读取未定义的属性‘路径’”。真的看不出我在哪里错过了 $location 注入,猜这就是原因。
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');
}])
}])
回答by dfsq
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.
除非你像这样调用这个函数gameLost($location)
(我怀疑)$location
最终会在本地函数范围内未定义,覆盖$location
父闭包范围内的服务。
So I think all you need to do is to remove $location
paremeter from gameLost
function definition:
所以我认为你需要做的就是$location
从gameLost
函数定义中删除参数:
function gameLost() {
var check = false;
$location.path('/game-over');
}