Nisham Mahsin
Nisham Mahsin

Reputation: 1399

Not Able to access $scope outside the function

I have a function called getMail()

$scope.getMail=function(){
  $http.get(APISource).
    success(function(data) {



  $scope.mail =data;



}).
error(function(data) {
    console.log("error");
  console.log(data);

});


}

in the success of this function i am saving the return data in $scope.mail; and also i have another function

function1() in the same controller but $scope.mail is not accessible.

please help.

Upvotes: 0

Views: 58

Answers (2)

Jonathan Tweedy
Jonathan Tweedy

Reputation: 131

Here is a fiddle that takes a few liberties to get something up and running grabbing fake data (from jsFiddle's api): http://jsfiddle.net/jetweedy/8vxvfcf7/

var app = angular.module('app', []);
app.controller('PhoneListCtrl', function ($scope, $http) {
    $scope.getMail = function () {
        $http.get("/echo/json/").
        success(function (data) {
            $scope.mail = data;
            console.log("success", $scope.mail);   
            $scope.function1();
        }).
        error(function (data) {
            console.log("error", data);
        });
    }
    $scope.function1 = function() {
        console.log("function1", $scope.mail);   
    }
    $scope.getMail();
});    

Upvotes: 0

wvdz
wvdz

Reputation: 16641

$http.get is performed asynchronously. This means that the setting of $scope.mail happens in a separate thread, and will most likely not be available in the same thread after calling the $http.get.

A possible solution could be to move everything you want to do with $scope.mail into the body of the success() callback:

...
success(function(data) {
  $scope.mail =data;
  function1();
})
...

Upvotes: 2

Related Questions