Anas Mosaad
Anas Mosaad

Reputation: 131

AngularJS promise and Local variables

I'm adding a component to an existing system. Most of the time, this component will deal with one item but there's a request to support multiple items. For example, visualizing certain item in a graph and if multiple items are selected, all will be included in the same graph.

They have a service to get a specific item, or all items but not selective items.

I have something like this

        for (var i = 0; i < $scope.items.length; i++) {
          var item = $scope.items[i];
          if (item.isSelected) {
            $scope.selectedItems[item.name] = { 
                /* certain initial properties are set here */ 
                nesteItems: []
            };
            thierService.getItem(item.id)
              .then(function(data) {
                // here I want to have access to item.name to reset the properties with correct values, 
                // for example:
                $scope.selectedItems[item.name].nesteItems = data.nestedItems;

              })
          }
        }

Is there a way using promise to do this? or has to work around it with closure?

Upvotes: 2

Views: 556

Answers (1)

Ilya
Ilya

Reputation: 326

I think it's convenient to join thierService.getItem call for all selected items to one promise and handle result.

var selectedItemsNames = [], promises = [];

for(var i = 0; i < $scope.items.length; i++) {
    var item = $scope.items[i];
    if(item.isSelected) {
        selectedItemsNames.push(item.name);
        promises.push(thierService.getItem(item.id));
    }
}

$q.all(promises).then(function(data) {
    for(i = 0; i < data.length; i++) {
        $scope.selectedItems[selectedItemsNames[i]] = { nesteItems: data[i].nestedItems };
    };
});

Upvotes: 1

Related Questions