在ui-router解析中使用$ scope

时间:2015-03-27 10:38:55

标签: angularjs angularjs-scope angular-ui-router

我正在使用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

有什么想法吗?

2 个答案:

答案 0 :(得分:19)

这是不可能的,范围尚未在此时初始化,因此您无法在解析对象中使用它。初始化后,您可以在控制器中访问示波器。整个解决方案是它在控制器初始化之前运行,以便您可以注入并直接访问范围内已解析的项目。

如果需要将变量传递给下一个状态,可以使用可用于解析的$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);
    }
}

答案 1 :(得分:0)

作为已接受解决方案的替代方案,它需要为服务器再次往返同一资源(如果从服务器/ 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: '...',
    });
}