Currently, I am working on developing a directive that can create a grid dynamically. The code I have written functions properly but there is one limitation where I need to explicitly mention the controller name 'DemoCtrl'. I am wondering if there is a way to automatically retrieve the current controller name from within the directive so that I can pass it to the buildColumn/buildRows functions for improved flexibility and efficiency?
angular.module('app').controller('DemoCtrl', function ($scope) {
$scope.controller = "DemoCtrl";
$scope.coldata = [
{name: 'Account'},
{name: 'Name'}
];
$scope.rowdata = [
{
"account": "ABC",
"name": "Jim"
},
{
"account": "DEF",
"name": "Joe"
},
{
"account": "GHI",
"name": "Fred"
}
];
});
angular.module('foxy.components.grid', [])
.controller('GridController', ['$scope', '$attrs', function ($scope, $attrs) {
}])
.directive('grid', function ($compile) {
return {
restrict: 'EA',
controller: 'GridController',
require: "^ngController",
scope: {
data: "=",
columns: "=",
controller: "="
},
link: function (scope, element, attrs, ctrl) {
scope.$watch('data', function () {
var el = $compile(buildGrid(scope.controller))(scope);
element.replaceWith(el);
element = el;
});
}
};
})
function buildGrid(controller) {
var html = "<table>";
html += "<thead>";
html += buildColumn(controller);
html += "</thead>";
html += "<tbody>";
html += buildRows(controller);
html +="</body>";
html += "</table>";
return html;
}
function buildColumn(controller) {
try {
var html = "";
var dom_el = document.querySelector('[ng-controller="' + controller + '"]');
var ng_el = angular.element(dom_el);
var ng_el_scope = ng_el.scope();
var colname = ng_el_scope.coldata;
html += "<tr>";
for (i = 0; i < colname.length; i++) {
html += "<th>";
html += colname[i]["name"];
html += "</th>";
}
html += "</tr>";
return html;
} catch (err) {
return "#error" + err;
}
}
function buildRows(controller) {
try {
var html = "";
var dom_el = document.querySelector('[ng-controller="' + controller + '"]');
var ng_el = angular.element(dom_el);
var ng_el_scope = ng_el.scope();
var colname = ng_el_scope.coldata;
var rows = ng_el_scope.rowdata;
for (j = 0; j < rows.length; j++) {
html += "<tr>";
for (data in rows[j]) {
html += "<td>";
html += rows[j][data];
html += "</td>";
}
html += "</tr>";
}
return html;
} catch (err) {
return "#error" + err;
}
}