简体   繁体   English

在指令的链接函数执行之前编译已包含的内容

[英]Compile transcluded content before directive's link function executes

I'm looking to compile the contents of transcluded stuff before the link function executes. 我正在寻找链接功能执行之前编译的东西的内容。 Currently, if I transclude an ng-bind-safe , the contents will not be added until after my link function. 当前,如果我排除了ng-bind-safe ,则直到链接功能之后才添加内容。

I can do a scope.$apply() in the link function (and it works) but I get console errors since the digest cycle is already in progress. 我可以在链接函数中执行scope.$apply() (并且可以工作),但是由于摘要周期已经在进行中,所以出现控制台错误。

Thoughts? 思考? Thank you! 谢谢!

During the compilation and linking phases ($compile and $link functions), you only have access to your template in your $compile function, and access to your scope and template in the $link function. 在编译和链接阶段($ compile和$ link函数),您只能在$ compile函数中访问模板,而在$ link函数中访问作用域和模板。 You do not have access to the rendered template yet because it hasn't happened yet. 您尚未访问渲染的模板,因为它尚未发生。 For that, you need to setup a watch expression, which you will provide call back functions for. 为此,您需要设置一个监视表达式,为其提供回调函数。 Angular will let you know when the value that you're watching has changed, and within this call back you have access to the rendered template. 当您正在观看的值更改时,Angular会通知您,并且在此回调中您可以访问渲染的模板。

This watch expression can only be done within the $link function because that is only place in the directive that you can properly access the scope. 该监视表达式只能在$ link函数内完成,因为这仅位于可以正确访问范围的指令中。

Here is an example: 这是一个例子:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM