我试图弄清楚是否有任何方法可以将索引参数传递给Promise的回调函数。例如。
serviceCall.$promise.then(function(object){ $scope.object = object; });
现在我想将数组索引参数传递为
serviceCall.$promise.then(function(object,i){ $scope.object[i] = something; });
能做到吗?请告诉我。
这是下面的代码
StudyService.studies.get({id: $routeParams.studyIdentifier}).$promise.then(function(study) { $scope.study = study; for(var i=0;i<study.cases.length;i++){ StudyService.executionsteps.get({id: $routeParams.studyIdentifier,caseId:study.cases[i].id}) .$promise.then(function(executionSteps,i){ $scope.study.cases[i].executionSteps = executionSteps; }); } });
您可以为此使用闭包。
例如,在您的代码中,使用类似以下内容的代码:
function callbackCreator(i) { return function(executionSteps) { $scope.study.cases[i].executionSteps = executionSteps; } } StudyService.studies.get({id: $routeParams.studyIdentifier}) .$promise.then(function(study) { $scope.study = study; for(var i=0;i<study.cases.length;i++) { var callback = callbackCreator(i); StudyService.executionsteps.get({id: $routeParams.studyIdentifier,caseId:study.cases[i].id}) .$promise.then(callback); } });