我有以下 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/