如何延迟子指令的编译阶段,因为父指令的范围具有它所需的所有数据

how to defer compilation phase of the child directives unti the scope of parent directive has all data it requires

本文关键字:指令 范围 因为 数据 何延迟 延迟 编译      更新时间:2023-09-26

我有以下html结构:

<my-parent-directive>
   <my-child-directive some-options="options">

以及应该实例化$scopemyParentDirective的控制器:

ng.module("some").directive("myParentDirective", ["someService", function(someService) {
    return {
        controller: function($scope) {
            someService.getData().then(function(options) {
                $scope.options = options;
            });
        }
    }
});

由于getData方法是异步的,并且可能需要一段时间才能返回对子指令至关重要的选项,因此我需要暂停子指令的编译''链接阶段,直到options到达。我该怎么做?

是的,实际上很有可能在收到数据后手动将子代码插入父指令中。下面是一个简短的示例:

app.directive('myParentDirective', ["someService", function(someService) {
    return {
        restrict: 'E',
        transclude: true,
        link: function($scope, element, attr, controller, transclude) {
            someService.getData().then(function(options) {
                 $scope.options = options;
                 // Grab the inner content of the directive
                 var innerContent = transclude($scope, function() {});
                 // And place it inside & recompile it
                 element.html(innerContent);
                 // For angular version 1.2.17 or lesser, compile the content
                 $compile(element.contents())($scope);
            });
        }
    };
}]);