How to create dynamic directive in angularjs? -
i have html , directive:
html:
<div id="box"> <button test>add</button> </div>
and directives:
// directive button tarefasapp.directive('test', function($compile){ homecoming 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 anchor document.getelementbyid('test2').setattributenode(att); // insert anchor within div#box document.getelementbyid('box').appendchild(el); }); } }); // directive dynamically created anchor tarefasapp.directive('test2', function($compile){ homecoming function(scope, element, attrs){ element.bind('click', function(){ alert('it worked!'); }); } });
when click <button test></button>
, first directive creates <a id="test2" test2>click me</a>
, append <div id="box"></div>
. far good. when click <a id="test2" test2>click me</a>
doesn't phone call directive test2
, don't know why. doing wrong?
what trying accomplish exactly?
i made illustration of how create new html element, , "compile" angular $compile 1 time add together in dom
http://codepen.io/antouank/pen/irkhl
var tarefasapp = angular.module('tarefas', []); // directive button tarefasapp .directive('test', ['$compile', function($compile){ homecoming { restrict: 'a', link: function(scope, element, attrs){ element .on('click',function(){ var newanchorele; // create new element newanchorele = document.createelement('a'); angular.element(newanchorele) .attr('anchor', '') .text('test'); // append in parent element element.parent().append(newanchorele); // compile new html $compile(newanchorele)(scope); }); } } }]); // directive anchor tarefasapp .directive('anchor', ['$compile', function($compile){ homecoming { restrict: 'a', link: function(scope, element, attrs){ console.log('anchor made'); setinterval(function(){ element.toggleclass('hidden'); },500); } } }]);
angularjs angularjs-directive
No comments:
Post a Comment