Javascript 从angularJS中的另一个指令向html添加指令
当我按下一个按钮时,一个模态显示出来。在那个模式中,我有一个Javascript 从angularJS中的另一个指令向html添加指令,javascript,html,angularjs,angularjs-directive,Javascript,Html,Angularjs,Angularjs Directive,当我按下一个按钮时,一个模态显示出来。在那个模式中,我有一个 单击按钮时,我会执行if检查,以确保它是正确的按钮。如果是-则添加另一个指令,而不是占位符 但我无法让它工作 这是我的指示: .directive('modalDirective', function(){ return { restrict: 'E', scope: { ctrl: '=', modalId: '@', },
单击按钮时,我会执行if检查
,以确保它是正确的按钮。如果是-则添加另一个指令,而不是占位符
但我无法让它工作
这是我的指示:
.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>'
}
});
.directive('modalDirective',function(){
返回{
限制:'E',
范围:{
ctrl:“=”,
莫达利德:“@”,
},
模板:['',
'',
'',
'',
“模态头”,
'',
'',
“{{ctrl.text}”,
'',
'',
'',
“结束”,
'',
'',
'',
''。加入(''),
链接:函数(范围、元素、属性){
范围$watch('modalId',功能(val){
if(val=='protocolModal'){
元素。查找('template-placeholder')。替换为('';
}
});
}
}
})
.directive('testDirective',function(){
返回{
限制:'E',
模板:“这是我们的另一个指令。”
}
});
您需要使用$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));
}
});
}
}])
.directive('modalDirective',['$compile',function($compile){
...
链接:函数(范围、元素、属性){
范围$watch('modalId',功能(val){
if(val=='protocolModal'){
元素。find('template-placeholder')。替换为($compile(“”)(scope));
}
});
}
}])
更新的小提琴:为什么要在
modalId
上观看?在以下情况下,您可以使用ng:
'<div class="modal-footer">',
'<test-directive data-ng-if="modalId == \'protocolModal\'"></test-directive>',
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>',
'</div>',
”,
'',
“结束”,
'',
这里有一个摆弄它的工具:将模板占位符替换为
<ng-if="protocolModal" test-directive></test-directive>
ng if将为您负责编译和销毁。这很好。如果有,为什么不使用ng呢。这将简化事情。
是一个指令还是一个虚拟元素?您正在替换内容,而无需编译it@NikosParaskevopoulos只是一个伪元素,应该用一个指令替换掉。