1

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

誰かが it 関数の要素変数宣言で ($rootScope) が何をしているのか説明できますか?

どんな効果があるのか​​わからない。

4

3 に答える 3

1

Angular でのコンパイルは 2 つのステップで行われます。$compile(template)ディレクティブは通常 DOM を変換するだけである前半のみを実行し (その他のより複雑な処理も同様に発生します ;))、「リンク関数」を返します。2 番目の部分は、リンク関数が特定のスコープを引数として呼び出されたときに実行されます。この部分では、ディレクティブでスコープを編集したり、動作を DOM イベントにリンクしたりできます。詳細については、公式ガイドを参照してください。

于 2014-11-21T10:34:03.363 に答える
1

この$compile関数は、スコープ変数から値を取得してバインディングを完了する関数を作成します。

によって作成された関数をスコープ変数で呼び出すと、$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" */
于 2014-11-21T10:21:29.920 に答える
1

未決定のサイクル$digestを待つ代わりに、その上の要素がすぐにコンパイルおよびレンダリングされるように、サイクルを強制するために使用されます$digest

于 2014-11-21T10:14:13.907 に答える