插入指令编程的角度 [英] Insert directive programatically angular

查看:115
本文介绍了插入指令编程的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我基本上要能够触发一个事件,然后有一个direcrtive编译并插入其自我DOM中的位置。
目前,我有这样的事情

So I basically want to be able to trigger an event and then have a direcrtive 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');
      }
    };
  });

我能看到物体厄尔尼诺与所有我需要的,但我不能将它插入到DOM ...
任何线索?

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?

推荐答案

您必须首先创建的DOM元素,然后编译它,并将它添加到文档中。事情是这样的:

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;
};

我创建了一个简单的例子在这里:<一href=\"http://plnkr.co/edit/n7SZpyeQ9nbjVSYA7ibB?p=$p$pview\">http://plnkr.co/edit/n7SZpyeQ9nbjVSYA7ibB?p=$p$pview

这篇关于插入指令编程的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆