如何在AngularJS中動態(tài)添加指令?我有一個非常簡化的版本,我正在做的是解決問題。我有一個簡單的directive。每當(dāng)您單擊一個元素時,它會添加另一個元素。但是,需要首先編譯它才能正確呈現(xiàn)它。我的研究引導(dǎo)我$compile。但是所有的例子都使用了一個復(fù)雜的結(jié)構(gòu),我真的不知道如何在這里應(yīng)用。小提琴在這里: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/
3 回答

慕桂英3389331
TA貢獻2036條經(jīng)驗 獲得超8個贊
你有很多毫無意義的jQuery,但在這種情況下$ compile服務(wù)實際上非常簡單:
.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 ); }; } };});
你會注意到我也重構(gòu)了你的指令,以便遵循一些最佳實踐。如果您對這些問題有任何疑問,請與我們聯(lián)系。
- 3 回答
- 0 關(guān)注
- 979 瀏覽
添加回答
舉報
0/150
提交
取消