Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/16656735/insert-directive-programmatically-angularjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...