gpt4 book ai didi

javascript - 嵌入和 ng-bind : how to render sub-directives?

转载 作者:行者123 更新时间:2023-12-02 14:44:32 24 4
gpt4 key购买 nike

最近我在理解如何动态更改 AngularJS 中指令的内容时遇到了问题。

首先,在我的 HTML 中,我有一个包含子指令的父指令。有时,我想刷新父指令的内容,但我尝试注入(inject)的子指令并未由 AngularJS 初始化。我做了一个 JSFiddle 来解释我的问题:http://jsfiddle.net/koj2e1th/2/

当我使用 $timeout 更新内容时,该指令未初始化:

$timeout(function(){
html = '<child-dir>TIMEOUT</child-dir>'
scope.content = $sce.trustAsHtml(html)
}, 2500)

我尝试使用 $compile (在其他问题上看到了这个),但我没有设法让它正常工作。你能解释一下如何让 $compile 在这种情况下工作,并让我的 child-dir 正确呈现吗?

提前致谢!

最佳答案

child-dir 指令未编译。在将指令添加到 DOM 之前,应该使用作用域对其进行编译。 click here

var demo = angular.module('demo', []);
demo.directive('parentDir', function($sce, $timeout, $compile) {
return {
restrict: 'E',
transclude: true,
template: '<div ng-bind-html="content"></div>',
link: function (scope, element, attrs, controller, transcludeFn) {
transcludeFn(function(html) {
$timeout(function() {
html = _.reduce(html, function(carry, domElement) {
if (domElement.outerHTML) {
return carry + domElement.outerHTML
} else {
return carry;
}
}, '')
scope.content = $sce.trustAsHtml(html)
})
})
var el = $compile( "<child-dir>TIMEOUT</child-dir>" )(scope );
element.parent().append( el );
}
}});

demo.directive('childDir', function($sce) {
return {
restrict: 'E',
transclude: true,
template: '<div>CHILD DIR</div>'
}});

关于javascript - 嵌入和 ng-bind : how to render sub-directives?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36720045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com