I'd like to pass a custom template, via bindings, into an AngularJS Component and render it using his scope. Something like this (pseudo-code, this is not working):
angular
.module('myApp', [])
.controller('mainController', ($scope) => {
$scope.getTemplate = () => (`
<div>
<span>{{$ctrl.name}}</span>
</div>
`)
})
.component('myComponent', {
controller: ($scope, $compile) => {
const $ctrl = $scope.$ctrl;
$ctrl.$onInit = () => {
$ctrl.name = 'Hello World!';
};
$ctrl.compileTemplate = () => $compile($ctrl.template())($scope);
},
bindings: {
template: '&'
},
template: `
<div>
My dynamic content: {{$ctrl.compileTemplate()}}
</div>
`
});
Usage:
<div ng-controller="mainController as $ctrl">
<my-component template="$ctrl.getTemplate()"></my-component>
</div>
Expected Result:
<div>
My custom content:
<div>
<span>Hello World!</span>
</div>
</div>
Is there any way to do it?
You can use the
$compileservice to create a directive to handle the DOM manipulation involved.The following working snippet implements an attribute directive
compilewhich compiles the input value of the attribute in the controller scope. It basically take your template and add it to the inner content of the element to which the directive is attached and finally compiles it.