我对我正在做的事情有一个非常简单的解释,可以让大家理解这个问题。
我有一个简单的指示。无论何时单击一个元素,它都会添加另一个元素。但是,为了正确地呈现它,首先需要编译它。
我的研究引导我使用$compile。但是所有的例子都使用了一个复杂的结构,我不知道如何在这里应用。
提琴在这里: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/
除了完善Riceball LEE的例子,添加了一个新的element-directive
newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)
添加一个新的attribute-directive到现有的元素可以这样做:
假设您希望动态地向span元素添加my-directive。
template: '<div>Hello <span>World</span></div>'
link: ($scope, $element, $attrs) ->
span = $element.find('span').clone()
span.attr('my-directive', 'my-directive')
span = $compile(span)($scope)
$element.find('span').replaceWith span
希望这能有所帮助。
如果你想动态添加一个使用内联模板的指令,Josh David Miller给出的答案非常有用。然而,如果你的指令利用templateUrl,他的答案将不会工作。以下是对我有效的方法:
.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: "app/views/modal.html",
link: function (scope, element, attrs) {
scope.modalTitle = attrs.modaltitle;
scope.modalContentDirective = attrs.modalcontentdirective;
},
controller: function ($scope, $element, $attrs) {
if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
var el = $compile($attrs.modalcontentdirective)($scope);
$timeout(function () {
$scope.$digest();
$element.find('.modal-body').append(el);
}, 0);
}
}
}
}]);
这里有很多毫无意义的jQuery,但是$compile服务在这种情况下实际上非常简单:
.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 );
};
}
};
});
您会注意到,为了遵循一些最佳实践,我也重构了您的指令。如果你有任何问题,请告诉我。