我是AngularJS的新手,并且需要编辑以下代码。
scope.findData = [];
scope.clientId;
scope.identityDocuments_a = [];
scope.getClientIdentityDocuments_a = function(clientID){
resourceFactory.clientResource.getAllClientDocuments({clientId: clientID, anotherresource: 'identifiers'}, function(data){
scope.identityDocuments_a = data;
});
};
scope.findOptions = function(value){
var i;
var deferred = $q.defer();
resourceFactory.clientResource.getAllClientsWithoutLimit({displayName: value, orderBy : 'id', officeId : scope.group.officeId, sortOrder : 'ASC', orphansOnly : true}, function (data) {
deferred.resolve(data.pageItems);
for (i = 0; i <= data.pageItems.length; i++) {
scope.clientId = data.pageItems[i].id;
scope.getClientIdentityDocuments_a(scope.clientId);
//<- I want to access scope.identityDocuments_a here
}
scope.findData = data.pageItems;
});
return deferred.promise;
};
这两个功能都在同一个控制器下。 我看了Accessing $scope variable from another method in the same controller Angularjs,但似乎没有用。我哪里错了?提前谢谢。
答案 0 :(得分:1)
好的,我看到了问题。你的getClientIdentityDocuments_a()正在使用回调函数。异步数据检索是单独进行的,因此在您想要使用它时不会设置该值。您可以通过返回承诺
来解决此问题scope.getClientIdentityDocuments_a = function(clientID){
var defer = $q.defer();
resourceFactory.clientResource.getAllClientDocuments(
{clientId: clientID,
anotherresource: 'identifiers'}, function(data){
scope.identityDocuments_a = data;
defer.resolve(data);
});
return defer.promise;
};
然后,在第二个函数中使用数据:
scope.getClientIdentityDocuments_a(scope.clientId).then(function(documents) {
// at this point, the scope.identityDocuments_a should be available,
// but you could just set it here, since the document variable is
// returning the same thing
console.dir(scope.identityDocuments_a) // should have the returned data
console.dir(documents) // should be the same as above
});
// Here, the documents will NOT be available, because this executes before
// the promise is resolved
console.dir(scope.identityDocuments_a) // [] or undefined
更新:为了澄清,如果在getClientIdentityDocuments_a中你要直接分配变量,例如
scope.getClientIdentityDocuments_a = function(clientID){
scope.identityDocuments_a = some_document;
};
您不需要承诺,您的代码也可以使用。但是,由于您是从异步源检索数据,因此您的第二个功能是在设置值之前尝试使用数据。