当我按下按钮时,会出现一个模式。在那个模式中我有一个
<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/