Reputation: 295
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?
Upvotes: 1
Views: 1162
Reputation: 17329
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;
}));
}
Upvotes: 6
Reputation: 1860
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;
});
});
Upvotes: 0
Reputation: 18339
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;
}
})
Upvotes: 0