$rootScope在此函数中做什么



在这个来自 Angular 文档的指令单元测试示例中:

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");
    });
});

有人可以解释一下($rootScope)在it函数中的元素变量声明中做了什么。

我不确定它有什么效果。

它用于强制$digest循环,以便立即编译和呈现其上面的元素,而不是等待不确定的$digest循环

$compile函数创建一个函数,该函数从范围变量中获取值以完成绑定。

当您使用 scope 变量调用 $compile 创建的函数时,它会用您作为参数给出的范围上的值替换所有绑定,并创建一个 DOM 元素。

例如:

$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" */

Angular 中的编译分两步完成。 $compile(template)只做前半部分,其中指令通常只是转换 DOM(;)也会发生其他更复杂的事情),并返回一个"链接函数"。第二部分是在使用特定范围作为参数调用链接函数时完成的。在这一部分中,指令可以编辑范围,将行为链接到DOM事件等。更多信息可以在官方指南中找到。

最新更新