Directives Demo - ng-transclude in $compile
by manoj
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<h1>Portal Wrapper directive</h1>
<div ng-app='portalng'>
<wrapper-static>
<h2>Wrap me Statically (boring)</h2>
</wrapper-static>
<hr/>
<wrapper-compile>
<h2>Wrap me Dynamically!</h2>
</wrapper-compile>
</div>
CSS
h1 {
font-weight: bold;
font-size: 18px;
margin-bottom: 10px;
}
h2 {
margin: 10px 0 5px;
}
.tag + .tag {
margin-left: 10px;
}
.tag {
display: inline-block;
border-radius: 5px;
padding: 2px 5px;
cursor: pointer;
}
.add {
border: solid 1px #88f;
background: #ddf;
}
.add:hover {
background: #bbf;
}
.remove {
border: solid 1px #8f8;
background: #dfd;
}
.remove:hover {
background: #bfb;
}
input {
width: 250px;
}
JavaScript
var app = angular.module('portalng', []);
app.directive('wrapperStatic', ['$http', '$compile', function ($http, $compile) {
return {
restrict: "E",
transclude: true,
template: "<div>Static Wrapper version {{wrapperVersion}}</div><hr/><div ng-transclude></div>",
scope:{},
link:function(scope, element, attr)
{
scope.wrapperVersion = "1.0";
}
};
}]);
app.directive('wrapperDynamic', ['$http', '$compile', function ($http, $compile) {
return {
restrict: "E",
transclude: true,
scope:{},
link:function(scope, element, attr, cntrlr, transclude)
{
scope.wrapperVersion = "1.0";
var tmpl = "<div>Dynamic Wrapper version {{wrapperVersion}}</div><hr/><div ng-transclude></div>";
thing = $compile(tmpl, transclude)(scope)//Doesn't work! "undefined is not a function"
element.append(thing);
}
};
}]);
app.directive('wrapperCompile', ['$http', '$compile', function ($http, $compile) {
return {
restrict: "E",
transclude: true,
scope:{},
compile:function(tElement, tAttrs, transclude){
var tmpl = "<div>Dynamic Wrapper using compile function version {{wrapperVersion}}</div><hr/><div ng-transclude></div><div>after</div>";
tElement.append(tmpl);
return function(scope, element, attr)
{
scope.wrapperVersion = "1.0";
}
}
};
}]);