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

时间:2014-10-30 14:23:31

标签: angularjs angularjs-directive

我有这个html和指令:

HTML:

<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!');
        });
    }   
});

当我点击<button test></button>时,第一个指令会创建<a id="test2" test2>Click me</a>并将其附加到<div id="box"></div>。到现在为止还挺好。但是,当我点击<a id="test2" test2>Click me</a>时,它不会调用directive test2而我不知道为什么。我做错了什么?

1 个答案:

答案 0 :(得分:1)

你想要完成什么?

我举了一个如何创建一个新的HTML元素的例子,以及&#34;编译&#34;一旦你将它添加到DOM

中,它就会带有角度$ compile

http://codepen.io/AntouanK/pen/irkHL

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);
      }
    }
}]);