以编程方式插入指令 AngularJS [英] Insert directive programmatically AngularJS
本文介绍了以编程方式插入指令 AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我基本上希望能够触发一个事件,然后编译指令并将其自身插入到 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
这篇关于以编程方式插入指令 AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文