Upon discovering the capabilities of ng-repeat
, I was convinced that it had to be achievable:
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 ) {
// Creating a new DOM context and binding it to the scope.
var template = angular.element( '<div class="wrap">' );
var context = $compile( template )( scope );
transclude( function( clone, theScope ) {
// In order for this to work properly, we must remove the directive attribute from the cloned element
// before compiling it back to its original scope. Failure to do so would result in an infinite loop.
// By utilizing the $attr property, we can determine which attribute variant was used (e.g., data-wrap-this-thing, x-wrap-this-thing).
// For more information on attribute normalization, refer to:
// 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 );
}
};
}]);