Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to promise's callback in angularjs

I am trying to figure out is there is any way to pass in an index argument to a promise's callback function. For instance.

serviceCall.$promise.then(function(object){
    $scope.object = object;
});

Now I want to pass in an array index parameter as

serviceCall.$promise.then(function(object,i){
    $scope.object[i] = something;
});

Can this be done? Please let me know.

Here is the code below

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;
      });
  }
});
like image 394
user3799365 Avatar asked Jul 25 '14 19:07

user3799365


1 Answers

you can use a closure for that.

for example, in your code, use something like:

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);
   }
});
like image 57
Yaron Schwimmer Avatar answered Oct 02 '22 12:10

Yaron Schwimmer