Search code examples
javascriptangularjsangularjs-ng-transclude

Transclude then replace with angularjs


I would like to create a directive that replaces :

   <my-overlay class="someOverlay">
      <h4>Coucouc</h4>
    </my-map-overlay>

With :

<div class="someOverlay default-overlay">
 <h4>Coucouc</h4>
</div>

The replace method is yet deprecated.

How to write a directive that manipules the DOM creating a div, adds the default-overlay class to the previous defined one, transcludes and replaces the <my-map> directive ?

Is it possible to divide the process as following : DOM manipulation in compile and transcluding in link?


Solution

  • This is the commit for 'replace' to be removed: https://github.com/angular/angular.js/commit/eec6394a342fb92fba5270eee11c83f1d895e9fb

    If you read some of the last comments it seems that replace may not be deprecated after all. However this could be a way to achieve what uou want:

    .directive('myOverlay', function(){
        return {
            restrict: 'E',
            template: '<div ng-transclude></div>',
            transclude: true,
            link: function (scope, element) {
                element.children()[0].setAttribute('class', element.attr('class') + ' default-overlay');
                element.replaceWith(element.children()[0]);
            }
        }
    });
    

    http://jsfiddle.net/b6ww0rx8/10/