41

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?

1

1 Answer 1

48

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

Sign up to request clarification or add additional context in comments.

9 Comments

How would I access $compile if I were creating the element outside of Angular?
Hi, would you please provide ideas on my new proposed API to make programmatically adding directives a simpler process? github.com/angular/angular.js/issues/6950 Thanks!
@Hengjie It needs to compile the element with reference to a particular scope (inside angular). There are no directives outside of angular. Directives are tied to scopes within your app. Alternately you can use the jQLite inside angular and do event handlers that way (angular.element('body')).
is this a normal practice, or considered against the angular grain?
It definitely feels it's against the Angular ways, though the alternative isn't any more prettier. I basically lazily triggered ng-include depending on an event and let ng-include handle the compilation and linking for me. If anyone is interested, I can dig up the code and add it as an answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.