AngularJS Dynamic Directive Templating
Enable a template url to be passed via an element attribute
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-sanitize.min.js"></script>
<div ng-app="app">
<div template="http://fiddle.jshell.net"></div>
<div tmpl="http://fiddle.jshell.net"></div>
</div>
JavaScript
var app = angular.module('app', []);
app.directive('template', ['$http', '$sce', '$compile', function($http, $sce, $compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$http.get(attrs.template).then(function(response) {
$compile(response.data)(scope, function(content) {
element.append(content);
});
});
}
}
}]);
app.directive('tmpl', ['$http', '$sce', '$compile', function($http, $sce, $compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$http.get(attrs.template).then(function(response) {
$compile(response.data)(scope, function(content) {
element.append(content);
});
});
}
}
}]);