如何在 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.
我有一个简单的指令
.每当您单击一个元素时,它就会添加另一个元素.但是,它需要先编译才能正确呈现.
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屋!