0

what shall I do to make the last row of code return a value?

$scope.runActionwithObjects = function() {

            for (var i = 0; i < $scope.Objects.length; i++) {
                console.log($scope.Objects[i]); //$scope is accessible
                $http.get($scope.Objects[i]["Commit"]).success(function (data) {
                    console.log($scope.Objects[i]);//return undefined
5
  • Return a value to where? (Where's the rest of the loop and the outer function?) Commented May 10, 2015 at 13:11
  • just imagine that this is the end of the loop, there is other piece of code, i don't want to show it Commented May 10, 2015 at 13:15
  • So show a simplified example that is complete in itself. Are you saying you want the inner .success() function to return a value to whatever calls .runActionwithObjects()? Please be clearer about what you're trying to do. Commented May 10, 2015 at 13:17
  • ok, I show you in fiddle, wait) Commented May 10, 2015 at 13:18
  • jsfiddle.net/Bronzer/cghwsx2m/1 Commented May 10, 2015 at 13:29

2 Answers 2

1

The problem is due to asynchrony of ajax requests.

When the success callback is executed, your loop has already finished and the i variable is already equal to $scope.Objects.length.

Try forEach. This function will create different closures for items in the array.

$scope.Objects.forEach(function(currentObject){
    console.log(currentObject); //$scope is accessible
    $http.get(currentObject["Commit"]).success(function (data) {
        console.log(currentObject);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

The reason your $scope.Objects[i] is undefined because the variable i is always = $scope.Objects.lenth + 1, for example you got 5 elements, the i will be 6, because the at the time of callback, it already got the last value.

One solution is to bind needed object to that method, so we can access it via this(we can not reference directly by closure to ref variable, because it's still stored the last item), for example:

           for (var i = 0; i < $scope.Objects.length; i++) {
               var ref = $scope.Objects[i];
               // console.log($scope.Objects[i]); //$scope is accessible
               var successCallback = (function (data) {
                   console.log(this);//return the ref

               }).bind(ref);
               $http.get('').success(successCallback);
           }
       }

1 Comment

@charlietfl: it should be $scope.Objects.length instead

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.