如何在angularjs中创建动态指令?

如何在angularjs中创建动态指令?,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我有以下html和指令: html: 当我单击时,第一条指令将创建一个单击我,并将其附加到。到现在为止,一直都还不错。但是当我单击clickme时,它不会调用指令test2,我也不知道为什么。我做错了什么?你到底想做什么 我举了一个例子,说明了如何创建一个新的HTML元素,并在将其添加到DOM中后使用angular$compile“编译”它 您已经有了具有相同id的元素,要使其正常工作,您需要每次生成一个新id。@HarishR我想您没有理解。唯一id为的元素是div和动态创建的锚a#test

我有以下html和指令:

html:


当我单击
时,第一条指令将创建一个
单击我
,并将其附加到
。到现在为止,一直都还不错。但是当我单击
clickme
时,它不会调用
指令test2
,我也不知道为什么。我做错了什么?

你到底想做什么

我举了一个例子,说明了如何创建一个新的HTML元素,并在将其添加到DOM中后使用angular$compile“编译”它


您已经有了具有相同id的元素,要使其正常工作,您需要每次生成一个新id。@HarishR我想您没有理解。唯一id为的元素是
div
和动态创建的锚
a#test2
我刚刚使用了您的代码并添加了
元素。在
指令('anchor')中('click')
函数中的
链接
,效果非常好。谢谢
<div id="box">
    <button test>Add</button>
</div>
// directive for button
tarefasApp.directive('test', function($compile){
    return function(scope, element, attrs){
        element.bind('click', function(){
            // create anchor
            el      = document.createElement('a');
            el.id   = 'test2';
            el.innerHTML = 'Click me';
            att     = document.createAttribute('test2');

            // set attribute to anchor
            document.getElementById('test2').setAttributeNode(att);

            // insert the anchor inside div#box
            document.getElementById('box').appendChild(el);
        });
    }
});

// directive for the dynamically created anchor
tarefasApp.directive('test2', function($compile){
    return function(scope, element, attrs){
        element.bind('click', function(){
            alert('it worked!');
        });
    }   
});
var tarefasApp =
angular.module('tarefas', []);

// directive for button
tarefasApp
.directive('test',
['$compile',
function($compile){

    return {
      restrict: 'A',
      link: function(scope, element, attrs){

        element
        .on('click',function(){

          var newAnchorEle;

          //  make the new element
          newAnchorEle = document.createElement('a');

          angular.element(newAnchorEle)
          .attr('anchor', '')
          .text('test');

          //  append it in the parent element
          element.parent().append(newAnchorEle);
          //  compile the new HTML
          $compile(newAnchorEle)(scope);
        });
      }
    }
}]);

// directive for the anchor
tarefasApp
.directive('anchor',
['$compile',
function($compile){

    return {
      restrict: 'A',
      link: function(scope, element, attrs){

        console.log('anchor made');

        setInterval(function(){
          element.toggleClass('hidden');
        },500);
      }
    }
}]);