gpt4 book ai didi

javascript - 从 angularJS 中的另一个指令向 html 添加指令

转载 作者:行者123 更新时间:2023-12-02 15:56:11 25 4
gpt4 key购买 nike

Fiddle here

当我按下按钮时,会出现一个模式。在那个模式中我有一个 <template-placeholder></template-placeholder>

单击按钮时,我执行 if-check以确保它是正确的按钮。如果是 - 则添加另一个指令而不是 placeholder .

但我无法让它工作。

这是我的指令:

.directive('modalDirective', function(){
return {
restrict: 'E',
scope: {
ctrl: '=',
modalId: '@',
},
template: ['<div id="{{modalId}}" class="modal fade" role="dialog">',
'<div class="modal-dialog">',
'<div class="modal-content">',
'<div class="modal-header">',
'<h4 class="modal-title">Modal Header</h4>',
'</div>',
'<div class="modal-body">',
'<p> {{ ctrl.text }} </p>',
'</div>',
'<div class="modal-footer">',
'<template-placeholder></template-placeholder>',
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>',
'</div>',
'</div>',
'</div>',
'</div>'].join(''),
link: function(scope, element, attrs) {
scope.$watch('modalId', function(val){
if(val == 'protocolModal'){
element.find('template-placeholder').replaceWith('<test-directive></test-directive>');
}
});
}
}
})

.directive('testDirective', function(){
return {
restrict: 'E',
template: '<div>this is our other directive speaking.</div>'
}
});

最佳答案

您需要使用$compile:

.directive('modalDirective', ['$compile', function($compile){
...
link: function(scope, element, attrs) {
scope.$watch('modalId', function(val){
if(val == 'protocolModal'){
element.find('template-placeholder').replaceWith($compile('<test-directive></test-directive>')(scope));
}
});
}
}])

更新后的 fiddle :https://jsfiddle.net/L0jns64m/3/

关于javascript - 从 angularJS 中的另一个指令向 html 添加指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537547/

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