BetaRide BetaRide - 6 months ago 16
AngularJS Question

How to add an inner wrapper to an element in angular?

I want an angular diretive to add an inner wrapper to a DOM element. Unfortunately it's not wrapping but replacing the inner part of the element. (see plunker)

So I have this html snippet:

<body ng-app="plunker">
<div class="outer" wrapp-my-content>
<label>Name: </label>
<input type="text" ng-model="name" />
<p>Hello {{name}}</p>
</div>
</body>


The directive should change this into

<body ng-app="plunker">
<div class="outer" wrapp-my-content>
<div class="inner-wrapper">
<label>Name: </label>
<input type="text" ng-model="name" />
<p>Hello {{name}}</p>
</div>
</div>
</body>


But what I get is

<body ng-app="plunker">
<div class="outer" wrapp-my-content>
<div class="inner-wrapper">
</div>
</div>
</body>


Directive Code:

var app = angular.module('plunker', []);

app.directive('wrappMyContent', function() {
return {
restrict: 'A',
transclude: true,
replace: true,
link: function(scope, element) {
var innerWrapper = angular.element('<div class="inner-wrapper" ng-transclude></div>');
element.prepend(innerWrapper);
}
}
});


How can I fix that?

Answer

You've mixed up ng-transclude and custom transclude by link:

1. Use template of directive (demo):

var app = angular.module('plunker', []);

//Recommended angular-way
app.directive('wrappMyContent', function() {
  return {
    restrict: 'A',
    transclude: true,
    template:'<div class="inner-wrapper" ng-transclude></div>',
    link: function(scope, element) {
    }
  }
});

2. Do transclude by custom link (demo) :

var app = angular.module('plunker', []);

//Equals transclude by your self
app.directive('wrappMyContent', function($compile) {
  return {
    restrict: 'A',
    scope:true,
    link: function(scope, element) {
      var innerContent = element.html();
      var innerWrapper = angular.element('<div class="inner-wrapper"></div>').append(innerContent);

      //Do compile work here.
      $compile(innerWrapper)(scope.$parent)
      element.empty().append(innerWrapper);

    }
  }
});
Comments