我想既然ng-repeat
可以做到,那一定是可能的:
http://plnkr.co/edit/stf02iPNvNnlsx1dsFZx?p=preview
app.directive( 'wrapThisThing', [ '$compile', function( $compile ) {
return {
restrict: 'A',
transclude: 'element',
link: function( scope, element, attrs, ctrl, transclude ) {
// Compile a new DOM context and bind it to our scope.
var template = angular.element( '<div class="wrap">' );
var context = $compile( template )( scope );
transclude( function( clone, theScope ) {
// To make this work, we need to remove our directive attribute from
// the clone before compiling it back to its original scope. If we
// don't do this, the compiler will re-evaluate our directive, creating
// an infinite loop.
// We can use the $attr property to figure out what attribute variation
// was used (ie. data-wrap-this-thing, x-wrap-this-thing, wrap:this:thing,
// etc.).
// See more about attribute normalization:
// http://www.bennadel.com/blog/2648-inspecting-attribute-normalization-within-directives-in-angularjs.htm
clone.removeAttr( attrs.$attr.wrapThisThing );
// Compile the transcluded element and bind it to its own scope. Then
// append it to our new context.
context.append( $compile( clone )( theScope ) );
});
element.replaceWith( context );
}
};
}]);