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.

1
  • 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). Commented Sep 3, 2015 at 22:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.