2017-01-01 33 views
0

我有這樣的代碼:

app.directive('foo', function($compile) { 
    return { 
    restrict: 'E', 
    scope: {}, 
    template: '<span>{{bar}}</span>', 
    compile: function(element, attrs) { 
     element.attr('title', '{{bar}}'); 
     return function(scope, element, attrs) { 
     scope.bar = 'hello'; 
     $compile(element)(scope); 
     } 
    } 
    } 
}); 

Plunkr: http://plnkr.co/edit/nFTgvYqoiFAthmjoizWS?p=preview

如果刪除了$compile位中的鏈接功能,則title屬性保持與表達式文本({{bar}}),而不是值('hello' );

任何人都可以解釋爲什麼?

我認爲(根據我在文檔中讀到的內容),這是編譯階段的目的 - 操縱模板併爲範圍和數據綁定的鏈接做準備。爲什麼我需要再次手動撥打$compile?模板是否已經編譯?

+1

也許相名字應該從'compile','preLink'被改變,'postLink'爲'postCompile ','preLink'和'postLink'在鏈接到範圍之前,postCompile階段可用於操作DOM,此時鏈接函數已創建,但未創建範圍。可以添加不需要編譯的DOM。如果添加了包含指令或需要插值的其他元素,則需要編譯和鏈接這些附加元素,以使指令和插值起作用。 – georgeawg

+1

要在編譯之前對模板進行處理,請爲'template'屬性提供一個函數:'template:function(tElement,tAttrs){}'。有關更多信息,請參閱[AngularJS綜合指令API參考 - 模板](https://docs.angularjs.org/api/ng/service/$compile#-template-)。 – georgeawg

+0

@georgeawg謝謝!你能指出我可以自己閱讀的參考嗎?我想知道我應該如何知道這件事(你怎麼知道它:)) – krulik

回答

1

也許相名字應改爲從compilepreLinkpostLinkpostCompilepreLinkpostLink。在鏈接到範圍之前,postCompile階段可用於操作DOM,此時鏈接函數已創建,但未創建範圍。可以添加不需要編譯的DOM。如果添加了包含指令或需要插值的其他元素,則需要編譯和鏈接這些附加元素,以使指令和插值起作用。

要在編譯之前對模板進行處理,請爲模板屬性提供一個函數:template: function(tElement, tAttrs) {}。有關更多信息,請參閱AngularJS Comprehensive Directive API Reference -- Template


可以共享一個參考「DOM可以添加,無需編譯,等等。」或者解釋你是如何發現這件事的?

的一些信息來源:

+0

請分享一個「不需要編譯就可以添加DOM」的參考。或者解釋你是如何發現這件事的?我真的很想理解這一點,併爲將來的挖掘留下自己的空間。 – krulik

相關問題