So I basically want to be able to trigger an event and then have a directive compile and insert its self to a position in the DOM. Currently I have something like this
//controller
angular.module('app').controller('MainCtrl', function ($scope, $compile) {
$scope.$on('insertItem',function(ev,attrs){
var el = $compile( "<chart></chart>" )( $scope );
$scope.insertHere = el;
});
});
// directive
angular.module('app')
.directive('chart', function () {
return {
template: '<div>My chart</div>',
restrict: 'E',
link: function postLink(scope, element, attrs) {
element.text('this is a chart');
}
};
});
I am able to see the object "el" with all that I need but I'm not able to insert it into the DOM... any clues?
You have to create the dom element first, then compile it and add it to the document. Something like this:
$scope.$on('insertItem',function(ev,attrs){
var chart = angular.element(document.createElement('chart'));
var el = $compile( chart )( $scope );
//where do you want to place the new element?
angular.element(document.body).append(chart);
$scope.insertHere = el;
};
I've created a simple example here: http://plnkr.co/edit/n7SZpyeQ9nbjVSYA7ibB?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With