Reputation: 109
var app = angular.module('app',[]);
app.directive('myGridTable',function($http){
var tbl_tpl = '<table>';
return {
restrict:'AE',
template:'{{tbl_tpl}}',
replace:true,
link:function(scope,element,attrib){
$http.get(attrib.src).success(function(response) {
scope.rows = response.data;
//rows and columns population....
angular.forEach(scope.rows,function(value,key){
console.log(value);
tbl_tpl = tbl_tpl + "<tr>";
angular.forEach(value,function(val,k){
tbl_tpl=tbl_tpl + "<td>" + val + "</td>" ;
});
tbl_tpl = tbl_tpl + "</tr>";
});
tbl_tpl = tbl_tpl + "</table>";
scope.tbl_tpl=tbl_tpl;
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
my query is that 'tbl_tpl' producing plain text if replace is off else showing error....hence do i have any way around of this problem
Upvotes: 2
Views: 62
Reputation: 520
Easiest would be to just use a directive. No need to complicate with controllers etc.
Directive:
.directive('tableList', function($http) {
return {
restrict:'E',
template: '<table><tr ng-repeat="row in rows"><td>{{row.property}}</td></tr></table>',
link:function(scope,element,attr){
scope.rows = [];
$http.get('/api/rows').then(function(response) {
scope.rows = response.data;
});
}
};
});
And then use the directive in you template:
<table-list></table-list>
Upvotes: 3
Reputation: 109
var app = angular.module('app',[]);
app.directive('myGridTable',function($http){
var tbl_tpl='';
var linkFunc = function(scope,element,attrib){
$http.get(attrib.src).success(function(response){
scope.rows = response.data;
tbl_tpl = tbl_tpl + "<thead>";
tbl_tpl = tbl_tpl + "<tr>";
angular.forEach(scope.rows[0],function(v,k){
tbl_tpl=tbl_tpl + "<th>" + k + "</th>" ;
});
tbl_tpl = tbl_tpl + "</tr>";
tbl_tpl = tbl_tpl + "</thead>";
tbl_tpl = tbl_tpl + "<tbody>";
angular.forEach(scope.rows,function(value,key){
tbl_tpl = tbl_tpl + "<tr>";
angular.forEach(value,function(v,k){
tbl_tpl=tbl_tpl + "<td>" + v + "</td>" ;
});
tbl_tpl = tbl_tpl + "</tr>";
});
tbl_tpl = tbl_tpl + "</tbody>";
element.html(tbl_tpl);
});
};
return{
restrict: 'AE',
link: linkFunc
};
});
after a little effort i was able to write the above code. and now my directive can produce a table with a provided json and with a dynamic template.
Upvotes: 0
Reputation: 978
All you need to do is get rid of that string concatenation, add a controller and then bind a ngRepeat to the scope.rows and it will create some rows for you using whatever template you want
JS
var app = angular.module('app', []);
app.controller('myGridTableCtrl', function($scope) {
});
app.directive('myGridTable',function($http){
return {
restrict:'AE',
scope,
link:function(scope,element,attrib){
$http.get(attrib.src).success(function(response) {
scope.rows = response.data;
});
}
};
});
HTML
<my-grid-table ng-controller="myGridTableCtrl">
<div ng-repeat="row in rows">
{{row.property}}
</div>
</my-grid-table>
Upvotes: 0