Add Angular directive in DOM
It's possible to add custom element in the DOM,
however, since the element is rendered by DataTables, we need to do some extra work in order for Angular
to recognize the directives.
- First, we need to define the directive in the DOM
- We then need to create the directive
-
Just this is not enough because the HTML element is added by DataTables. So Angular does not know
its existence. So we need to compile it so that Angular takes into account the customBtn directive.
To do that, we need to create another directive that wraps the table. This wrapper will be used to
compile the customBtn directive once the table is rendered.
angular.module('showcase.customButton', ['datatables'])
.controller('CustomElementCtrl', CustomElementCtrl)
.directive('datatableWrapper', datatableWrapper)
.directive('customElement', customElement);
function CustomElementCtrl(DTOptionsBuilder, DTColumnBuilder) {
var vm = this;
vm.dtOptions = DTOptionsBuilder.fromSource('data.json')
// Add your custom button in the DOM
.withDOM('<"custom-element">pitrfl');
vm.dtColumns = [
DTColumnBuilder.newColumn('id').withTitle('ID'),
DTColumnBuilder.newColumn('firstName').withTitle('First name'),
DTColumnBuilder.newColumn('lastName').withTitle('Last name').notVisible()
];
}
/**
* This wrapper is only used to compile your custom element
*/
function datatableWrapper($timeout, $compile) {
return {
restrict: 'E',
transclude: true,
template: '',
link: link
};
function link(scope, element) {
// Using $timeout service as a "hack" to trigger the callback function once everything is rendered
$timeout(function () {
// Compiling so that angular knows the button has a directive
$compile(element.find('.custom-element'))(scope);
}, 0, false);
}
}
/**
* Your custom element
*/
function customElement() {
return {
restrict: 'C',
template: '
My custom element
'
};
}