动态地添加AngularJS指令 [英] Dynamically add 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.
我的研究使我 $编译
。但是,所有的例子都使用一个复杂的结构,我真的不知道该如何适用于此。
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戴维·米勒解决方案:
http://jsfiddle.net/paulocoelho/fBjbP/2/
推荐答案
您有很多无谓的jQuery在那里,但是$编译服务实际上是超级简单的在这种情况下:
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屋!