AngularJS和UI路由器:为什么$state.go()和$location.path()在交互式控制台中不起作用

AngularJS & UI Router : Why do $state.go() and $location.path() not work in interactive console?

本文关键字:path 交互式 不起作用 控制台 location go 路由器 UI 为什么 state AngularJS      更新时间:2023-09-26

请参阅此 plunker : https://run.plnkr.co/mTN6nIsUkxFtiZLx/#/state1

https://plnkr.co/edit/KYQG3OMPoCthEDcus12Y?p=info

它基本上是 UI 路由器文档中提供的演示代码。为了以编程方式测试状态之间的导航,我制作了使用 $state.go(stateName)$location.path(stateUrl) 的控制器函数,它们都可以正常工作。

控制器的代码:

myApp.controller('mainController', ['$scope', '$state', '$location',  function($scope, $state, $location) {
  $scope.usingState = function() {
    console.log('usingState() called');
    $state.go('state2');
  };
  $scope.usingLocation = function() {
    console.log('usingLocation() called');
    $location.path('/state2');
  };
}]);

但是,在交互式控制台(开发人员工具(中,它不起作用。如果我执行以下操作:

$state = angular.element(document).injector().get('$state');
$state.go('state2');

$location = angular.element(document).injector().get('$location');
$location.path('/state2');

什么也没发生。为什么?

我希望能够在交互式控制台中进行快速测试...

您提到的上述代码似乎可以在控制台上运行。在 plunker 中,您无法从文档中获取injector因为 plunker 在加载角度的<iframe>内运行代码。

要测试功能,请打开 UI 路由器示例应用程序。 在控制台中输入以下代码并观察状态转换:

angular.element(document).injector().get('$state').go('about');

更新:

在您提供的 plunker 中,我将角度版本 1.1.5 更改为 1.2.0(1.1.5 之后发布的版本(,一切似乎都正常。以下是 1.2.0-rc.3 和 1.2.0更改日志,它们可能会帮助您追踪为什么它在以前的版本中不起作用。

更新了普伦克。希望这有帮助!