javascript - 如何推迟子指令的编译阶段,直到父指令的范围具有所需的所有数据

标签 javascript angularjs

我有以下 html 结构:

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

以及 myParentDirective 的 Controller ,它应该实例化 $scope:

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

关于javascript - 如何推迟子指令的编译阶段,直到父指令的范围具有所需的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28297361/

相关文章:

javascript - AngularJS 函数无法更新 json 字符串值

angularjs - 如何在 AngularJS 中使 textarea 不允许或忽略换行符/换行符/返回

javascript - JQuery droppable() 无法识别 "this"对象引用

javascript - Angular 服务参数错误

javascript - 如何在表单字段输入中生成简短的唯一代码?

javascript - 台式机和笔记本电脑的含义是什么?

angularjs - ng-repeat 仅重复唯一值(合并重复项)

javascript - 数据更改时 ng 类不刷新

javascript - 在 Vue 中以编程方式更改自动完成所选项目

javascript - html中的水平滑动