在 AngularJS UI 路由器中使用 $state.go() 移动后如何访问新的 $scope

How do i access the new $scope after moving with $state.go() in AngularJS UI Router

嘿伙计们,我在用 $state.go 更改状态后试图到达新范围。

$state.go("newState").then(function () {
      // doesn't work
     $state.current.$scope.variable = "abc";
     
     // doesn't work as well because it's referencing the old $scope
     $scope.variable = "def";
                })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

您可以改为在状态更改中传递变量

$state.go("newState", {variable: "abc"})

在状态配置中添加参数

$stateProvider
.state('newState', {
    url: '/newState',
    params: {
        variable : null
    },
    templateUrl: 'newState.html',
    controller: 'newStateCtrl'
});

然后在你的 newStateCtrl 中,注入 $stateParams 并获取变量

$stateParams.variable