2
$scope.openDocImg = function(id, e){
    var data = [];

    ...

    $http.post("/showDocument", cid).then(function(response){
        data = response.data.slice(0);
        console.log(data);
    });

    console.log(data.length);  //displays 0
    console.log(data);

    ...
}

I don't get it completely why the data in the post method is filled with content and the outside isn't. Is it because of the variable scope inside and outside the function?

And how do I copy the content to the outer scope?

temp
  • 519
  • 7
  • 18

1 Answers1

1

Since $http.post method is executed asynchronous, console.log(data.length); statement is executed before you're receiving response from server.

So that's why you're receiving 0 when you're trying to log the length of data.

You should use a callback function.

function postRequest(callback){
  $http.post("/showDocument", cid).then(function(response){
    callback(response.data.slice(0));
  });
}

$scope.openDocImg = function(id, e){
    var data = [];

    ...

    postRequest(function(data){
       console.log(data.length); 
       console.log(data);
    });

    ...
}
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128