slee
slee

Reputation: 339

Storing HTTP Response as a Controller Variable

I'm wondering if there's a way to take an $http response and store it to a controller variable as opposed to the $scope. For example:

app.controller('testController', function($scope, $http) {

    this.result = 5; // I'd like to store the result here instead of on $scope

    $http({
            method: 'POST',
            url: 'example/',
            params: {test_param :'test_parameter'}
        }).success(function(result) {
            $scope.result = result.data; // This works
            this.result = result.data; // This does not work
        });

The error I end up getting when trying to use "this.result" is:

TypeError: Cannot set property 'result' of undefined

So it seems like when you're inside "success" you only have access to $scope and not necessarily to variables within the controller.

What I'm trying to do is localize the scope of the "result" variable in case I want to use the same name in other controllers. I guess if I use $scope then I'll have to keep track of all the variables across all controllers?

In any case, I have a feeling I'm using the wrong model here but any guidance would be appreciated.

Thanks.

Upvotes: 0

Views: 2895

Answers (1)

muenchdo
muenchdo

Reputation: 2181

The reason for your issues is that this is not referring to the controller inside the callback. There is multiple ways to overcome this, one of of them would be:

$http({
    method: 'POST',
    url: 'example/',
    params: { test_param: 'test_parameter' }
}).success(function(result) {
    $scope.result = result.data; // This works
    this.result = result.data; // Should also work now
}.bind(this));

Refer to this question for more info on the topic.

Upvotes: 4

Related Questions