Search code examples
javascriptajaxangularjsangularjs-scope

how to access the url inside .success of the $http.get method in angularjs


I have the following controller

var app = angular.module('callapp', []);
app.controller('eController', function($scope, $http, $log) {
    $scope.urlString = []; //this is filled with values

    for( var i=0; i<3; ++i)
    {
        var currentURL = $scope.urlString[i];
        $http.get(currentURL)
        .success( function(response) {
            //how do I access currentURL here?
            $log.info(this.currURL) //this is printing "undefined"
        });
    }

The urls are generated dynamically, and I have to get data from these urls. The urls are generated before the for loop executes (and the url requests are asynchronous).

I tried $.ajax(currentURL) instead of $http.get method, but I got the same result - "undefined".

Is there any way I can access the currentURL and the current value of 'i' inside the .success(function ())?


Solution

  • currentUrl is easily accessible, and since you're making AJAX requests inside a for loop, you will always get i to be the last index value because the renderer will print the value when the AJAX req gives 200 which will take some time and within that time for loop would have executed, so always the last index value will be there in i. For this, you have to use IIFE

    For the purpose of Demo, I'm using a Fake Online REST API - http://jsonplaceholder.typicode.com/

    RUNNING DEMO: http://plnkr.co/edit/djPMu4UH9t9BeGwBcUMI

    HTML:

    <body ng-app="callapp" ng-controller="eController">
    </body>
    

    JS:

    var app = angular.module('callapp', []);
    app.controller('eController', function($scope, $http, $log) {
        $scope.baseUrl = "http://jsonplaceholder.typicode.com/posts/";
        $scope.urlString = [
          $scope.baseUrl + '1',
          $scope.baseUrl +'2',
          $scope.baseUrl + '3'
        ]; //this is filled with values
    
    
        for( var i=0; i<3; ++i) {
           (function(index) {
            var currentURL = $scope.urlString[i];
            $http.get(currentURL)
            .success( function(response) {
                $log.info(index+1, currentURL);
            });
          })(i);
        }
    });
    
    app.$inject = ['$scope', '$http', '$log'];