1

I am developing an app with angularjs and ionic. There I have an array with ids. And from all these ids I need to have a name. Now I tried it with the code below:

var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
var arrayWithNames = [];

for (var j = 0; j < arrayWithIds.length; j++) {
    ResourceService.get(arrayWithIds[j]).then(function(resource) {
        arrayWithNames.push(resource.Name);                  
    },function(error) {
        alert(error.message);        
    });               
}

$scope.resources = arrayWithNames;

It is all ok when I debug. I always get the name back. But in $scope.resources there is nothing, it is empty, also the array arrayWithNames.

Do I miss something? What is the problem?

Thanks.

5
  • 1
    Have you tried adding in the return arrayWithNames; at the end of the for loop? See whether that works? Commented Jul 15, 2015 at 7:13
  • Thanks for your answer. I have tried it and it didn't work. Commented Jul 15, 2015 at 7:17
  • Maybe it is important to say that the whole code above is also in a web api call. Commented Jul 15, 2015 at 7:23
  • 1
    Please check the response variable names. Is Name or name. Commented Jul 15, 2015 at 7:26
  • @Ramesh: Thank you very much. That was the fault. Commented Jul 15, 2015 at 7:32

1 Answer 1

2

The ResourceService.get() call is asynchronous (and also a Promise), and this line

$scope.resources = arrayWithNames;

is getting called before the ResourceService.get() callback.

You can drop arrayWithNames and directly push to $scope.resources:

var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
$scope.resources = [];

for (var j = 0; j < arrayWithIds.length; j++) {
    ResourceService.get(arrayWithIds[j]).then(function(resource) {
        $scope.resources.push(resource.Name);                  
    },function(error) {
        alert(error.message);        
    });               
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.