![](/img/trans.png)
[英]AngularJS : How to access the directive's scope in transcluded content?
[英]Compile transcluded content before directive's link function executes
我正在尋找鏈接功能執行之前編譯的東西的內容。 當前,如果我排除了ng-bind-safe
,則直到鏈接功能之后才添加內容。
我可以在鏈接函數中執行scope.$apply()
(並且可以工作),但是由於摘要周期已經在進行中,所以出現控制台錯誤。
思考? 謝謝!
在編譯和鏈接階段($ compile和$ link函數),您只能在$ compile函數中訪問模板,而在$ link函數中訪問作用域和模板。 您尚未訪問渲染的模板,因為它尚未發生。 為此,您需要設置一個監視表達式,為其提供回調函數。 當您正在觀看的值更改時,Angular會通知您,並且在此回調中您可以訪問渲染的模板。
該監視表達式只能在$ link函數內完成,因為這僅位於可以正確訪問范圍的指令中。
這是一個例子:
app.directive('tmTime', function() {
return {
restrict: 'A',
template: '<div>{{time}}</div><div ng-transclude></div>',
transclude: true,
link: function (scope, element, attr) {
scope.time = 'Its hammer time!';
scope.$watch('time', function(newVal, oldVal) {
// this is your call back function
// within here, you have access to the rendered template
alert(element[0].outerHTML); // (it's hammer time! in first div, transcluded contents in second div)
});
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.