我使用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!
我还尝试了一些孤注一掷的尝试,例如向resolve对象添加作用域,如下图所示,但没有成功。
scope: $scope有什么想法吗?
发布于 2015-03-27 18:52:51
这是不可能的,作用域在那时还没有初始化,所以你不能在resolve对象中使用它。您可以在初始化之后访问控制器中的作用域。解析的全部要点是,它在控制器初始化之前运行,以便您可以注入并直接访问作用域中已解析的项。
如果需要将变量传递给下一个状态,可以通过使用$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);
}
}发布于 2016-08-24 02:56:38
作为被接受的解决方案的替代方案,它需要为相同的资源再往返到服务器(如果您从服务器/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: '...',
});
}https://stackoverflow.com/questions/29298699
复制相似问题