Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert directive programmatically AngularJS

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?

like image 507
climboid Avatar asked May 20 '13 19:05

climboid


1 Answers

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

like image 169
joakimbl Avatar answered Oct 04 '22 14:10

joakimbl