1

I'm having a problem trying to use "this" with angular functions (specifically $http.get) inside a controller.

Example:

Javascript- (psuedo code)

...
.controller('testController')
{
   $http.get(data)
  {
     this.Stuff = data;
  }
}
...

HTML-

<div ng-controller='testController as test'>
{{test.Stuff}}
</div>

When trying to access test.Stuff in the html, it is empty.

I understand that there is a scope issue, but shouldn't I be able to access the controller's 'this' inside of the $http function?

3 Answers 3

6

You'll notice that this inside of your success callback refers to window (the global object). Your success callback is being called with window as the context because functions that are not members of other functions are invoked with the window object as the context for the function. If you want this to refer to your controller instance you must bind that context to the function. You can use angular.bind to accomplish this.

.controller('testController')
{
   $http.get(data).success(angular.bind(this, function(data) {
     this.Stuff = data;
  }));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Did you test this? 1. you need to add data as the callback parameter 2. you need to add another closing parentheses 3. i couldn't get this to work.
0

Try it this way:

controller('testController')
{
   var self = this;

   $http.get(data)
  {
     self.Stuff = data;
  }
}

I typically use the scope like this:

.controller('testController', function($scope) {
{
   $http.get(data)
  {
     $scope.Stuff = data;
  }
})

2 Comments

I've already used both and know they both work. thank you for your suggestion but it doesn't really answer my question. I understand that 'this' changes insides $http, but I'm trying to understand why it would since $http's scope should be inside the outer controller scope.
Have you put a breakpoint inside the $http callback to see what this references. I bet it references the $http service or window and not the controller.
0

Assign the data to your scope in the http callback like so:

app.controller('testController',function($scope,$http) {
    $http.get(url).success(function(response) {
        $scope.stuff = response;
    });
});

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.