如何在AngularJS中动态添加指令? [英] How can I dynamically add a directive in AngularJS?
问题描述
我所做的工作非常精简,可以解决问题.
I have a very boiled down version of what I am doing that gets the problem across.
我有一个简单的directive
.每当您单击一个元素时,它都会添加另一个元素.但是,必须先对其进行编译才能正确呈现.
I have a simple directive
. Whenever you click an element, it adds another one. However, it needs to be compiled first in order to render it correctly.
我的研究使我成为$compile
.但是所有示例都使用了一个复杂的结构,我真的不知道如何在这里应用它.
My research led me to $compile
. But all the examples use a complicated structure that I don't really know how to apply here.
小提琴在这里: http://jsfiddle.net/paulocoelho/fBjbP/1/
JS在这里:
var module = angular.module('testApp', [])
.directive('test', function () {
return {
restrict: 'E',
template: '<p>{{text}}</p>',
scope: {
text: '@text'
},
link:function(scope,element){
$( element ).click(function(){
// TODO: This does not do what it's supposed to :(
$(this).parent().append("<test text='n'></test>");
});
}
};
});
Josh David Miller的解决方案: http://jsfiddle.net/paulocoelho/fBjbP/2/
Solution by Josh David Miller: http://jsfiddle.net/paulocoelho/fBjbP/2/
推荐答案
其中有很多毫无意义的jQuery,但是在这种情况下,$ compile服务实际上是超级简单:
You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:
.directive( 'test', function ( $compile ) {
return {
restrict: 'E',
scope: { text: '@' },
template: '<p ng-click="add()">{{text}}</p>',
controller: function ( $scope, $element ) {
$scope.add = function () {
var el = $compile( "<test text='n'></test>" )( $scope );
$element.parent().append( el );
};
}
};
});
您会注意到,我也重构了您的指令,以便遵循一些最佳实践.如果您有任何疑问,请告诉我.
You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.
这篇关于如何在AngularJS中动态添加指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!