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


i want angular diretive add inner wrapper dom element. unfortunately it's not wrapping replacing inner part of element. (see plunker)

so have 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 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 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 fix that?

you've mixed ng-transclude , custom transclude 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. transclude custom link (demo) :

var app = angular.module('plunker', []);  //equals transclude 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

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -