Angularjs routing:无法读取undefined的属性'path'

vit*_*lym 4 javascript angularjs

我试图在控制器中的函数内部触发angularJS路由,但它会抛出"Uncaught TypeError:无法读取未定义的属性'路径'".无法真正看到我错过了$ 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: '/'
  });
});
Run Code Online (Sandbox Code Playgroud)

当我使用路由器时,我的游戏控制器的一部分

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');
Run Code Online (Sandbox Code Playgroud)

}])

dfs*_*fsq 6

看看这段代码:

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

除非你像这样调用这个函数gameLost($location)(我怀疑)$location将在本地函数作用域中以未定义的方式结束,$location从父闭包范围覆盖服务.

所以我认为您需要做的就是$locationgameLost功能定义中删除参数:

function gameLost() {
        var check = false;
        $location.path('/game-over');
}
Run Code Online (Sandbox Code Playgroud)