Angular: Directive Transclude
http://angularjs.org/
by mmansion
HTML
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.min.js"></script>
<!-- directive template -->
<script type="text/ng-template" id="MyDirective.html">
<div id="template">
<!-- directive content -->
<div>DIRECTIVE TEMPLATE:</div>
<div id="directive">
<div>DIRECTIVE SCOPE:</div>
<div class="selected">{{ selected.name }}</div>
<span class="item" ng-repeat="item in items" ng-click="onselect(item)">{{ item.name }}</span>
</div>
<!-- transclude container transclusion scope is a sibling of directive scope -->
<div id="transclude" ng-transclude></div>
</div>
</script>
<div id="parent" ng-controller="Parent">
<div>PARENT SCOPE:</div>
<my-directive items="colors" selected="color" onselect="onSelect">
<!-- transclusion is not a child, but a sibling of the directive scope -->
<div>TRANSCLUDE SCOPE:</div>
<select ng-model="color" ng-options="c.name for c in colors"></select>
</my-directive>
Currently selected:
<select ng-model="color" ng-options="c.name for c in colors"></select>
<div style="height:20px; background-color: {{ color.name }};"></div>
</div>
CSS
div, input, b, span { padding: 4px; margin: 3px; }
#parent { border: 3px solid orange }
#template { border: 3px solid olive }
#directive { border: 3px solid purple }
#transclude { border: 3px solid pink }
span { background-color: #eee; cursor: pointer; }
.selected { font-weight: bold; font-size: 30px; line-height: 40px; margin: 0px; padding: 0px; }
JavaScript
var myModule = angular.module( 'myApp',[] );
function Parent( $scope )
{
$scope.colors = [
{ name: 'black' },
{ name: 'purple' },
{ name: 'red' },
{ name: 'blue' },
{ name: 'teal' },
{ name: 'orange' },
{ name: 'yellow' }
];
$scope.color = $scope.colors[0];
$scope.onSelect = function( color ) {
$scope.color = color;
}
}
function MyDirective( $scope )
{
}
myModule.directive('myDirective', function()
{
return {
restrict: 'E',
replace: true,
scope: {
selected: '=',
items: '=',
onselect: '='
},
transclude: true,
templateUrl: 'MyDirective.html',
controller: 'MyDirective',
}
});