Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSteve Ono
4,761 PointsWhat is the scope of $scope.todos in the callback function inside dataService.getTodos(...)?
In the below example, what is the scope of $scope.todos in the callback function inside dataService.getTodos(...)? Since it's a callback function, it seems like it would be executed within the service "dataService". Also, why is it necessary to include "response" as an argument for that callback function. Why cant you just use response inside the callback function without the argument. Since the response object exists at the time of the callback execution, why does it need to be fed into the function as an argument?
angular.module("todoListApp", [])
.controller('mainCtrl', function($scope, dataService) {
$scope.learningNgChange = function() {
console.log("An input changed!");
};
$scope.helloWorld = dataService.helloWorld;
dataService.getTodos(function(response){
console.log(response.data);
$scope.todos = response.data;
});
})
.service('dataService', function($http) {
this.helloWorld = function() {
console.log("This is a dataService method!");
};
this.getTodos = function(callbackArg){
$http.get('mock/todos.json').then(callbackArg);
};
});
2 Answers
akak
29,445 PointsThe $scope inside the callback function corresponds to the $scope of a controller. Services don't have their own scope, only controllers (and directives, but a bit different one) have scopes. So after you fetch data by a function from the service, you can assign it to a scope you want. You could use $scope of this controller, or some other controller. It's up to you and your needs.
As for callback function - it's just a function, it doesn't have anything extra when created. The response is not a global 'var response = response' that you could use as you want inside any function. If you do 'function() { something}' you have an empty function. You need to pass the response object created by the parent (let's call it that way - I'm sure it should be called other name :P) to the callback function. If you do 'function(response){}' now you have that response object inside a callback function.
Steve Ono
4,761 Pointsthanks