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?

8
  • Can you show asynchronous callbacks? Commented May 10, 2016 at 8:22
  • What exactly do you mean by "modify"? Can you share input and desired output please? Commented May 10, 2016 at 8: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 Commented May 10, 2016 at 8:24
  • 1
    You need to put $scope.someArray = []; out of your function Commented May 10, 2016 at 8: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. Commented May 10, 2016 at 8:27

1 Answer 1

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)
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! This is it. Could you give me some hint to understand it?
A closure will create a new scope for each iteration. Here is a great article on how closures work... stackoverflow.com/questions/111102/…
Thank you second time, Thalaivar.

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.