在 ui-router resolve 中使用 $scope

Using $scope in ui-router resolve

我正在使用 ui-router resolve 以便从服务中获取一些数据。

问题是我需要从父 $scope 获取一个值才能调用该服务,如下所示。

resolve: {
              contactService: 'contactService',
              contacts: function ($scope, contactService) {
                  return contactService.getContacts($scope.parentCtrl.parentObjectId);
              }
          }

我不断收到 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

还尝试了一些孤注一掷的尝试,例如向解析对象添加范围,如下所示,但没有成功。

scope: $scope

有什么想法吗?

那是不可能的,此时作用域尚未初始化,因此您不能在解析对象中使用它。您可以在初始化后访问控制器中的范围。 resolve 的全部要点是它在 before 控制器初始化之前运行,以便您可以注入并直接访问范围内已解析的项目。

如果您需要将变量传递给下一个状态,您可以使用可用于解析的 $stateParams 对象来实现。您可以在更改状态时向其添加数据,例如:

在您的模板中,如果您的范围内有一个 objectId:

<a ui-sref="statename({'id': objectId})">Change states</a>

或者在你的控制器中:

$scope.go('statename', {'id': $scope.objectId});

然后您可以使用 $stateParams:

在您的解决方案中检索它
resolve: {
    contactService: 'contactService',
    contacts: function ($stateParams, contactService) {
        return contactService.getContacts($stateParams.id);
    }
}

作为已接受解决方案的替代方案,它需要为同一资源再次往返服务器(如果您从 server/api 获取值),您可以 $watch 父级来自子控制器。

function ParentController($http) {
  var vm = this;
  $http.get(someResourceUrl).then(function(res) {
    vm.someResource = res.data;
  });
}

function ChildController($scope) {
  // wait untill the parent gets the value
  var unwatch = $scope.$watch('parent.someResource', function(newValue) {
    if (newValue) {
      // the parent has the value, init this controller
      init(newValue);
      // dispose of the watcher we no longer need
      unwatch();
    }
  });
  function init(someResource) {
    // ... do something
  }
}

function routerConfig($stateProvider) {
  $stateProvider
    .state('parent', {
      url: '/parent',
      controller: 'ParentController',
      controllerAs: 'parent',
      templateUrl: '...',
    })
    .state('parent.child', {
      url: '/child',
      controller: 'ChildController',
      controllerAs: 'child',
      templateUrl: '...',
    });
}