Skip to content Skip to sidebar Skip to footer

Angular Share Variable Betwen $http.get And Controller

I can't pass the content of one variable inside $http.get() to outside of this method... it's always undefined. I tested with $rootScope, but it didn't work. controller('myControl'

Solution 1:

There are two problems here:

  • The content parameter in your success handler is shadowing the content variable in your controller.
  • You are trying to write content to the console before it has a value. This will not work because $http.get() is asynchronous.

To fix these problems:

  • Remove the content parameter. It serves no purpose.
  • Use the content variable inside your success callback.
controller('myControl', function ($scope, $http) {
    var content;

    $http.get('../Json/data.json').success(function (data) {
        content = data;

        console.log(content);
        $scope.dataJson = content;
    }).error(function (data, status, headers, config) {
        $scope.dataJson = "ERROR";
    });
});

Solution 2:

First of all, you don't wait for asynchronous $http.get() to finish so console.log() will always print out undefined.

Second, maybe you could think about using then() rather than success(). http://bit.ly/18xIHio

The following should work just fine for you.

/* JS */
app.controller('myControl', function($http) {
    var ctrl = this;

    $http.get('http://www.data.fi/data.json').then(function (response) {
        ctrl.content = response; // use response.data to get the payload
    }).catch(function (error) {
        ctrl.content = error;
    }).finally(function() {
        console.log(ctrl.content); 
    });
});

<!-- HTML -->
<divng-controller="myControl as ctrl">{{ ctrl.content | json }}</div>

Solution 3:

Don't pass content in your parameters for success function. This is a global variable. Passing it would create scoping issues. Also use console.log both inside success function and outside it.

Post a Comment for "Angular Share Variable Betwen $http.get And Controller"