Loop $http


#1

Hello everyone,

this is my code :

$http.get('lienversmonapi?level='+niveau[0]+'&value='+valeur[0]).then(function(response){
    $scope.element0 = response.data;
});
$http.get('lienversmonapi?level='+niveau[1]+'&value='+valeur[1]).then(function(response){
    $scope.element1 = response.data;
});
$http.get('lienversmonapi?level='+niveau[2]+'&value='+valeur[2]).then(function(response){
    $scope.element2 = response.data;
});
$http.get('lienversmonapi?level='+niveau[3]+'&value='+valeur[3]).then(function(response){
    $scope.element3 = response.data;
});
$http.get('lienversmonapi?level='+niveau[4]+'&value='+valeur[4]).then(function(response){
    $scope.element4 = response.data;
});

I would like to know, how I can do to avoid to write 5 times the same code…

I’ve tried a for loop, but it didn’t work…

Thanks for helping !


#2

Hello,

I think you can do something like that :

 $scope.element = [];
    var callMe = function(i){
        if(i >= 0){
            $http.get('lienversmonapi?level='+niveau[i]+'&value='+valeur[i]).then(function(response){
                $scope.element[i] = response.data;
                callMe(i--);
            });
        }
    }
    callMe(maxValue);

Or just use a for loop :

$scope.element = [];
for(var i = 0; i < maxValue; i++)
    $http.get('lienversmonapi?level='+niveau[i]+'&value='+valeur[i]).then(function(response){
        $scope.element[i] = response.data;
    });
}

Instead of using element0 in your view jst use element[0]


#3

Thanks for the reply,

But I can’t call $scope.element[1] in my view

I can only call the last element…


#4

In your view : {{element[0}} should work.

I typed this : http://play.ionic.io/app/9f4d47206c35

Hope it can help.


#5

Thank you, it works !
What if I want 5 jokes, and make an ng-repeat in my view?


#6

I updated the code: http://play.ionic.io/app/9f4d47206c35