What is $rootScope doing in this function?

527 views Asked by At

In this example of a directive unit test from the Angular docs:

describe('Unit testing great quotes', function() {
    var $compile;
    var $rootScope;

    // Load the myApp module, which contains the directive
    beforeEach(module('myApp'));

    // Store references to $rootScope and $compile
    // so they are available to all tests in this describe block
    beforeEach(inject(function(_$compile_, _$rootScope_){
      // The injector unwraps the underscores (_) from around the parameter names when matching
      $compile = _$compile_;
      $rootScope = _$rootScope_;
    }));

    it('Replaces the element with the appropriate content', function() {
        // Compile a piece of HTML containing the directive
        var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
        // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
        $rootScope.$digest();
        // Check that the compiled element contains the templated content
        expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
    });
});

Can someone explain what ($rootScope) is doing in the element variable declaration in the it function.

I not sure what effect it has.

3

There are 3 answers

0
tomaoq On

The $compile function creates a function that grabs values from a scope variable to complete bindings.

When you call the function created by $compile with a scope variable, it replaces all bindings with a value on the scope you gave as an argument, and create a DOM element.

For example :

$rootScope.age = 15;
$scope.age = 52;

var element = $compile("<div>Tom is {{age}}</div>")($rootScope);
/* element is a div with text "Tom is 15" */

var element2 = $compile("<div>Tom is {{age}}</div>")($scope);
/* element2 is a div with text "Tom is 52" */
0
hon2a On

Compilation in Angular is done in two steps. $compile(template) does just the first half, where directives usually just transform the DOM (and other, more complicated stuff happens as well ;)), and returns a "linking function". The second part is done when the linking function is called with a particular scope as argument. In this part, directives can edit the scope, link behavior to DOM events, etc. More can be found in the official guide.

1
Michael On

It is used to force a $digest cycle so that the element above it is compiled and rendered immediatly instead of waiting for an undetermined $digest cycle