How can I use $ compile more than once?
I am using Angular and I am trying to add directives to the page dynamically. I am using the $ compile service in a controller like:
var element1 = document.createElement('myDirective');
var element2 = document.createElement('myDirective');
$compile(element1)(scope);
$compile(element2)(scope); // error on this line
document.body.appendChild(element1);
document.body.appendChild(element2);
This works fine for element 1, but when I run $ compile (element2) (scope) I get the following error:
TypeError: undefined is not a function
at http://localhost/Vendor/AngularJs/angular.min.js:6564:36
at forEach (http://localhost/Vendor/AngularJs/angular.min.js:332:20)
at nodeLinkFn (http://localhost/Vendor/AngularJs/angular.min.js:6563:11)
at compositeLinkFn (http://localhost/Vendor/AngularJs/angular.min.js:6086:13)
at publicLinkFn (http://localhost/Vendor/AngularJs/angular.min.js:5982:30)
at MyController.addElements (http://localhost/Scripts/MyController.js:26:31)
What am I doing wrong?
+3
source to share
1 answer
First, DOM manipulation in controllers is bad practice. To do this, you need to study the instructions ng-show, ng-if, ng-switch or ng-repeat.
If you are really sure this is what you want, move the DOM manipulation into the directive and add new elements to the element provided in the link function, not the document.body.
Then try using cloneAttachFn in your link function call:
var myDirective = document.createElement('myDirective');
var linkFunction = $compile(myDirective);
linkFunction(scope, function (clone) {
// element instead of document.body, we're in another directives link function
element.append(clone);
};
linkFunction(scope, function (clone) {
element.append(clone);
};
+1
source to share