HappySnowman
HappySnowman

Reputation: 109

Looping through Angular API calls

I have a list of items and I want to pass the selected items to the API and check if that item exists or not.

$scope.submitButton = function() {
    for (var i=0; i < $scope.selectedItems.length; i++) {
        console.log($scope.selectedItems[i]); // item2
        myService.checkItem($scope.selectedItems[i])
        .success(data, status, header, config) {
           var myData = data;
           console.log(myData); 
        })
    }
}

When I select item2 and click the button, I only want the service to return data for item2 but it returns data for item1, item2, and item4 (item3 does not exist). How could I modify my code to only return data for item2?

Upvotes: 0

Views: 679

Answers (1)

user8639395
user8639395

Reputation:

Try this:

Use track by $index when you iterating the objects as like the following HTML code.while you click pass the $index value in the submit button event.

HTML:

<div ng-repeat="item in selected_items track by $index" ng-click="submitButton($index)"></div>

Angular JS:

$scope.submitButton = function(index) {
for (var i=0; i < $scope.selectedItems.length; i++) {
    console.log($scope.selectedItems[index]); // item2
    myService.checkItem($scope.selectedItems[index])
    .success(data, status, header, config) {
       var myData = data;
       console.log(myData); 
    })
  }
}

Upvotes: 1

Related Questions