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

标签 javascript html angularjs angularjs-directive

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/

相关文章:

javascript - 使用 ajax、php 和 javascript 验证通过后插入到数据库

javascript - ng-model 没有在 safari 浏览器中的命令粘贴上更新

javascript - 修改嵌入的 Angular Directive(指令)

javascript - 如何在不滚动页面的情况下在加载时滚动 div 内的表格

html - 我的下拉菜单的内容关闭得太快

html - CSS:将 img 相对于 div 对齐

javascript - 如何从mysql/knexjs中提取重复输入错误(1062)的键

javascript - 将数组连接到自身是否比遍历数组以创建更多索引更快?

javascript - 包含还是包含?

javascript - 如何创建自定义事件并使用 Javascript 触发它