AngularJS bind-compiled-html
by Jonathan Hieb
HTML
<body ng-app="MyApp" ng-controller="MyController as my">
<div>{{my.test}}</div>
<div ng-repeat="directive in my.directiveHtmlList"
bind-compiled-html="directive.directiveHtml">
</div>
<div ng-repeat="directive in my.directiveNameList"
bind-directive="directive.directiveName">
</div>
</body>
JavaScript
(function() {
angular
.module('MyApp', [])
.controller('MyController', MyController)
.directive('bindCompiledHtml', bindCompiledHtml)
.directive('bindDirective', bindDirective)
.directive('firstDirective', firstDirective)
.directive('secondDirective', secondDirective);
function MyController() {
this.test = 'hello world';
this.directiveHtmlList = [
{'directiveHtml': '<first-directive />'},
{'directiveHtml': '<second-directive />'}
];
this.directiveNameList = [
{'directiveName': 'first-directive'},
{'directiveName': 'second-directive'}
];
}
function bindCompiledHtml($compile) {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
var html = $scope.$eval($attrs.bindCompiledHtml),
toCompile = angular.element(html);
$element.append($compile(toCompile)($scope));
}
};
}
function bindDirective($compile) {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
var html = $scope.$eval($attrs.bindDirective),
toCompile = angular.element('<' + html + '>');
$element.append($compile(toCompile)($scope));
}
};
}
function firstDirective() {
return {
restrict: 'E',
template: '<div>First Directive Apple</div>'
};
}
function secondDirective() {
return {
restrict: 'E',
template: '<div>Second Directive Salami</div>'
};
}
})();