2

I have simple function in scope which calls some service several times. I want to append retrieved data to the array in the scope.

$scope.foo = function(){
   $scope.someArray = [];
   for(var i = 0; i < something.length; i++){
       var name = something[i];
       FooService.someMethod($resource, name).then(function (result) {
          if(result){
             $scope.someArray.push(name);
          }
       }
   }
}

The problem is someArray in a result is filled with set of the same values. It's the last pushed value repeated something.length times.

How should I handle scope objects if I want to modify them from callbacks?

Arkadiusz Kałkus
  • 17,101
  • 19
  • 69
  • 108
  • Can you show `asynchronous callbacks`? – Satpal May 10 '16 at 08:22
  • What exactly do you mean by "modify"? Can you share input and desired output please? – Sergiu Paraschiv May 10 '16 at 08:23
  • Pick out the items by a specific id and update them. What does your data look like? It would be much easier to help if you provide information on how your things are set up, at the moment this is very vague – Patrick May 10 '16 at 08:24
  • 1
    You need to put `$scope.someArray = [];` out of your function – Tmb May 10 '16 at 08:25
  • @SergiuParaschiv Maybe it's to general question. Basically I want to know how should I properly access scope array inside a callback. As I've written - presented code produces as a result array of the same elements, to be precise it's only last element repeated n times. – Arkadiusz Kałkus May 10 '16 at 08:27
  • Then please provide all of the relevant code. Where does `someresult` come from? Looks to me it's a scoping issue with that `for` loop. We need to see that code to provide an answer. – Sergiu Paraschiv May 10 '16 at 08:29
  • @Patrick Values I want to store in the array are strings. In the callback I push set of various strings to array. – Arkadiusz Kałkus May 10 '16 at 08:29
  • I've updated the code to be more precise and less general. I'm sorry for being vague in my previous description of the problem. – Arkadiusz Kałkus May 10 '16 at 08:32

1 Answers1

3

The for loop is sync where as your $http calls are not.

$scope.foo = function(){
   $scope.someArray = [];
   for(var i = 0; i < something.length; i++){
       (function(i){
       var name = something[i];
       FooService.someMethod($resource, name).then(function (result) {
          if(result){
             $scope.someArray.push(name);
          }
       }
      })(i)
   }
}
Thalaivar
  • 23,282
  • 5
  • 60
  • 71