user2405469
user2405469

Reputation: 2003

Angular js use of controller in this example

I am reading the Angular JS documentation I am looking at this example:

// testing controller
    describe('MyController', function() {
       var $httpBackend, $rootScope, createController;

       beforeEach(inject(function($injector) {
         // Set up the mock http service responses
         $httpBackend = $injector.get('$httpBackend');
         // backend definition common for all tests
         $httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});

         // Get hold of a scope (i.e. the root scope)
         $rootScope = $injector.get('$rootScope');
         // The $controller service is used to create instances of controllers
         var $controller = $injector.get('$controller');

         createController = function() {
           return $controller('MyController', {'$scope' : $rootScope });
         };
       }));

My question is what purpose the createController serves, I don't really understand why it is there or what the last line does where $controller is returned or what it has to do with the $scope.

It is the second grey section that contains code underneath the header: Unit testing with mock $httpBackend.

Help would be greatly appreciated.

Upvotes: 0

Views: 47

Answers (1)

Mark
Mark

Reputation: 2135

$controller returns an instance of MyController from the first grey section. To give the controller some context, it passes the $rootScope into the instantiation of the controller. Hence when you execute the controller (as shown in subsequent it() blocks) the controller runs and kicks off the $http.get('/auth.py') request.

Upvotes: 1

Related Questions