0

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.

slee
  • 287
  • 2
  • 7
  • 15
  • Note that you don't need to save the variable as an instance variable of the controller. A local variable will do. Just use `var result = 5;` and `result = response.data;` (of course, the `result` argument of the success callback must be renamed to avoid a clash). – JB Nizet Sep 03 '15 at 22:58

1 Answers1

4

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.

Community
  • 1
  • 1
muenchdo
  • 2,161
  • 1
  • 17
  • 30