首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ui中使用$scope -路由器解析

在ui中使用$scope -路由器解析
EN

Stack Overflow用户
提问于 2015-03-27 18:38:55
回答 2查看 11.5K关注 0票数 15

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

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

代码语言:javascript
复制
resolve: {
              contactService: 'contactService',
              contacts: function ($scope, contactService) {
                  return contactService.getContacts($scope.parentCtrl.parentObjectId);
              }
          }

我一直在找Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

我还尝试了一些孤注一掷的尝试,例如向resolve对象添加作用域,如下图所示,但没有成功。

代码语言:javascript
复制
scope: $scope

有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-03-27 18:52:51

这是不可能的,作用域在那时还没有初始化,所以你不能在resolve对象中使用它。您可以在初始化之后访问控制器中的作用域。解析的全部要点是,它在控制器初始化之前运行,以便您可以注入并直接访问作用域中已解析的项。

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

在您的模板中,如果您的作用域中有一个objectId:

代码语言:javascript
复制
<a ui-sref="statename({'id': objectId})">Change states</a>

或者在你的控制器中:

代码语言:javascript
复制
$scope.go('statename', {'id': $scope.objectId});

然后,您可以使用$stateParams在解析中检索它

代码语言:javascript
复制
resolve: {
    contactService: 'contactService',
    contacts: function ($stateParams, contactService) {
        return contactService.getContacts($stateParams.id);
    }
}
票数 20
EN

Stack Overflow用户

发布于 2016-08-24 02:56:38

作为被接受的解决方案的替代方案,它需要为相同的资源再往返到服务器(如果您从服务器/api获得值),您可以从子控制器$watch父控制器。

代码语言:javascript
复制
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: '...',
    });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29298699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档