以编程方式插入指令 [英] Insert directive programmatically angular
本文介绍了以编程方式插入指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我基本上希望能够触发一个事件,然后进行伪指令编译并将其自身插入DOM中的某个位置. 目前我有这样的东西
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');
}
};
});
我可以看到对象"el"以及所有我需要的东西,但是我无法将其插入到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;
};
我在这里创建了一个简单的示例: http://plnkr.co/edit/n7SZpyeQ9nbjVSYA7ibB ?p =预览
I've created a simple example here: http://plnkr.co/edit/n7SZpyeQ9nbjVSYA7ibB?p=preview
这篇关于以编程方式插入指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文