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

olu adesina
olu adesina
23,007 Points

how is the service triggered in the first place

in the example on the video the services works once the page is loaded doesn't the controller have to be trigger first by the ng-change directive before any injected services can work

angular.module("todoListApp", [])

.controller('mainCtrl', function($scope,dataService) {
 $scope.helloWorld = function(){ 
    console.log("Hello there! This the helloWorld controller function, in the    mainCtrl!");
  };

  $scope.helloConsole= dataService.helloConsole;

   $scope.todos= dataService.getTodos();





  })
  .service('dataService',function($http){

        this.helloConsole = function() {
          console.log('testing helloConsole');
  };
        this.getTodos= $http.get('mock/todos.json')
        .then(function(response){
          console.log(response.data);
          return response.data;
        })

  });

1 Answer

The service is grabbing data from our mock database via http method and the get method which is a shortcut method off the $http. The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model. The model being ng-model="todo.name". Which is bind its value in the element to an object in the $scope The controller itself is already in play watching for expressions and events because of its $scope. Which all our function and services is ran thru. Nothing happens without the say of the $scope. Hopefully that made sense because i just now got done watching the video myself. Please if im wrong in any way let me know so i can correct myself.