How can I dynamically add a directive in AngularJS?
You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:
.directive( 'test', function ( $compile ) { return { restrict: 'E', scope: { text: '@' }, template: '<p ng-click="add()">{{text}}</p>', controller: function ( $scope, $element ) { $scope.add = function () { var el = $compile( "<test text='n'></test>" )( $scope ); $element.parent().append( el ); }; } };});
You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.
In addition to perfect Riceball LEE's example of adding a new element-directive
newElement = $compile("<div my-directive='n'></div>")($scope)$element.parent().append(newElement)
Adding a new attribute-directive to existed element could be done using this way:
Let's say you wish to add on-the-fly my-directive
to the span
element.
template: '<div>Hello <span>World</span></div>'link: ($scope, $element, $attrs) -> span = $element.find('span').clone() span.attr('my-directive', 'my-directive') span = $compile(span)($scope) $element.find('span').replaceWith span
Hope that helps.
Dynamically adding directives on angularjs has two styles:
Add an angularjs directive into another directive
- inserting a new element(directive)
- inserting a new attribute(directive) to element
inserting a new element(directive)
it's simple. And u can use in "link" or "compile".
var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );$element.parent().append( newElement );
inserting a new attribute to element
It's hard, and make me headache within two days.
Using "$compile" will raise critical recursive error!! Maybe it should ignore the current directive when re-compiling element.
$element.$set("myDirective", "expression");var newElement = $compile( $element )( $scope ); // critical recursive error.var newElement = angular.copy(element); // the same error too.$element.replaceWith( newElement );
So, I have to find a way to call the directive "link" function. It's very hard to get the useful methods which are hidden deeply inside closures.
compile: (tElement, tAttrs, transclude) -> links = [] myDirectiveLink = $injector.get('myDirective'+'Directive')[0] #this is the way links.push myDirectiveLink myAnotherDirectiveLink = ($scope, $element, attrs) -> #.... links.push myAnotherDirectiveLink return (scope, elm, attrs, ctrl) -> for link in links link(scope, elm, attrs, ctrl)
Now, It's work well.