Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript AngularJS Basics (1.x) Services in Angular Using Services To Get Data

Steve Ono
Steve Ono
4,761 Points

What 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
akak
29,445 Points

The $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.