Skip to content

Instantly share code, notes, and snippets.

@levonlee
Last active October 27, 2015 16:56
Show Gist options
  • Select an option

  • Save levonlee/0cd28353cdea6909c28d to your computer and use it in GitHub Desktop.

Select an option

Save levonlee/0cd28353cdea6909c28d to your computer and use it in GitHub Desktop.
Various Ways of using AngularJS Transclude

The following shows different usage of Transclude in AngularJS

  • Add static element on top of existing ones
  • Add dynamic element on top of existing ones
  • Wrap existing elements with a dynamic element which is added later
  • Change the current element's attribute or class

jsFiddle

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<div ng-app="myapp" ng-controller="parentCtrl">
<div foo>
<div style="color: red;">Line 1</div>
<div style="color: blue;">Line 2</div>
</div>
<div foo2>
<div style="color: red;">Line 1</div>
<div style="color: blue;">Line 2</div>
</div>
<div foo3>
<div style="color: red;">Line 1</div>
<div style="color: blue;">Line 2</div>
</div>
<div foo4>
<div style="color: red;">
<p>transclude: true removes the existing elements. </p>
<p>You will have to run the transclude funciton otherwise the existing elements will disappear</p>
<p>Simply run the transclude function, and it will not do anything</p>
</div>
<div style="color: blue;">Line 2</div>
</div>
</div>
angular.module('myapp',[])
.directive("foo", function() {
return {
transclude: true,
template: "<h2>Add element using static template. Existing elements will be wrapped in ng-transclude</h2><ng-transclude></ng-transclude>"
};
})
.directive("foo2", function() {
return {
transclude: true,
link: function(s,e,a,c,t) {
t(function(clone) {
var wrapper = angular.element('<h2>Add element using dynamic template. Existing elements will not be wrapped</h2>');
e.append(wrapper); // Add element
e.append(clone); // remove the transcluded content and add back
});
}
};
})
.directive("foo3", function() {
return {
transclude: true,
link: function(s,e,a,c,t) {
a.$set('style','border: 1px;'); // set attribute
a.$set('class','class1 class2'); // set attribute
t(function(clone) {
var wrapper = angular.element('<div>Wrap existing elements with a dynamically added element</div>');
wrapper.append(clone);
e.append(wrapper); // Add clone
});
}
};
})
.directive("foo4", function() {
return {
transclude: true,
link: function(s,e,a,c,t) {
t(function(clone) {
e.append(clone); //
});
}
};
})
.controller('parentCtrl',function($scope) {});
normalize_css: no
panel_jss: 0
panel_css: 0
wrap: b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment