Dynamic data-title with ng-repeat in AngularJS - javascript

I'm looking for a solution to show dynamic header in the angular table for some of its <td>
my data looks like
let data = [
{
id: 1,
name: 'name',
fields: {
field 1: { value: '123'},
field 2: {value: 'macx'}
}
},
{
id: 2,
name: 'name2',
fields: {
field 1: { value: '456'},
field 2: {value: '3333'}
}
}
]
it should show in one table, I mean fields attr's should show as extra columns in the same table
note: fields are dynamic and I can't know it exactly so I need to do something like this in code
if any idea how I can get that work or any other idea to get the view as explained
<tr ng-repeat="data in $data">
<td data-title="'id'|translate"
sortable="'id'">
{{data.id}}
</td>
<td ng-repeat="(key, value) in data.fields track by $index"
ng-show="columnsHash[key]"
data-title="customFieldsTitles[$index]"
filterable="{field:'fields', type:'text', align:'LEFT'}"
data-title-text="customFieldsTitles[$index]">
{{value && value.value || ''}}
</td>
<td ng-show="columnsHash.totalBenefitTarget"
data-title="'target_total_benefit' | translate"
sortable="'total_benefit_target'"
style="text-align:center;"
filterable="{field: 'total_benefit_target', type:'number_range', options: {min: Number.MIN_VALUE, max: Number.MAX_VALUE}}">
{{data.total_benefit_target | number: 0}}
</td>
<td ng-show="columnsHash.totalBenefitActual"
data-title="'actual_total_benefit' | translate"
sortable="'total_benefit_actual'"
style="text-align:center;"
filterable="{field: 'total_benefit_actual', type:'number_range',
options: {min: Number.MIN_VALUE, max: Number.MAX_VALUE}}">
{{data.total_benefit_actual | number: 0}}
</td>
<tr>
showing columns order is important so writing it like code above
thanks in advance

angular table use scope.$column to render tb cols so I solved that by using scope binding
<table ng-table="tableParams" ng-init="initTable()">
<td ng-repeat="(key, value) in data.fields"
data-title="'Custom Field'"
sortable="'fields'"
filterable="{field:'fields', type:'text', align:'LEFT'}">
{{value && value.value || ''}}
</td>
</table>
in controller
var tableColumns;
$scope.initTable = function(){
var scope = this;
$timeout(function(){
tableColumns = scope.$columns;
});
};
after loading data for table call this function to update columns title
function updateCustomFields(){
var columnTemplate, index;
var colCount = 0;
if (!tableColumns) {
return;
}
tableColumns.map(function(col, i){
if (col.title() === 'Custom Field'){
columnTemplate = col;
index = i;
tableColumns.splice(index, 1);
return true;
}
});
for(var fieldLabel in $scope.customFieldsHash){
(function (label) {
var column = angular.copy(columnTemplate);
column.id = column.id+colCount/10;
column.title = function(){ return label; };
tableColumns.splice(index+colCount, 0, column);
colCount++;
})(fieldLabel);
}
}

Related

AngularJS - Sorting data ascending / descending when column is clicked

I have the following view code:
<tr ng-repeat="c in clients | orderBy:'code'">
<td>{{c.firstname}} {{c.lastname}}</td>
<td>{{c.telephone}}</td>
<td>{{c.location}}</td>
<td>{{c.code}}</td>
</tr>
I want to change the orderBy:'code' when column is clicked, assume that the user clicked on the column location, i want the orderBy condition to change to 'location' instead of code, and to be in this form
<tr ng-repeat="c in clients | orderBy:'location'">
angular.module('app', []).controller('ctrl', function($scope) {
$scope.prefix = '+';
$scope.sort = '';
$scope.sortFn = function(name) {
$scope.prefix = $scope.prefix == '-' ? '+' : '-';
$scope.sort = $scope.prefix + name;
}
$scope.arrow = function(name){
if($scope.sort.indexOf(name) != -1)
return $scope.prefix == '+' ? '↑' : '↓';
return '';
}
$scope.clients = [
{ name: 'Tom', age: 30 },
{ name: 'Max', age: 20 },
{ name: 'Sam', age: 40 },
{ name: 'Liza', age: 25 },
{ name: 'Henry', age: 35 }
]
})
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
th{
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app='app' ng-controller='ctrl'>
<thead>
<tr>
<th ng-click='sortFn("name")'>Name {{arrow("name")}}</th>
<th ng-click='sortFn("age")'>Age {{arrow("age")}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="c in clients | orderBy:sort">
<td>{{c.name}}</td>
<td>{{c.age}}</td>
</tr>
</tbody>
</table>
Use datatables.js for automate sorting
https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
write ng-click on the column and call a function like setSortByParameter and set the field sortBy.
and now write the orderBy as below.
<tr ng-repeat="c in clients | orderBy:'{{sortBy}}'">

bind multidimensional array with vuejs

I am building a dynamic table on my front end side, and at the end i need to know what was inserted on each cell of my table since it is editable, so i did this on my html:
<table class="table table-responsive">
<tbody>
<tr v-for="(row,idx1) in tableRows" :class="{headerRowDefault: checkHeader(idx1)}">
<td class="table-success" v-for="(col,idx2) in tableCols"><input v-model="items[idx1][idx2]" type="text" class="borderTbl" value="HEY"/></td>
</tr>
</tbody>
</table>
as you guys can see. i set inside the input a v-model with items[idx1][idx2] so i can pass the value to that line and columns, it is not working like this, i don't know how to set it.
This is my javascript:
export default {
name: 'app',
data () {
return {
table: {
rows: 1,
cols: 1,
key: 'Table',
tableStyle: 1,
caption: '',
colx: []
},
hasHeader: true,
hasCaption: true,
insert: 1,
idx2: 1,
items: []
}
},
computed: {
tableStyles () {
return this.$store.getters.getTableStyles
},
tableRows () {
return parseInt(this.table.rows)
},
tableCols () {
return parseInt(this.table.cols)
}
expected items array:
items:[
["john","Micheal"]
["john","Micheal"]
["john","Micheal"]
["john","Micheal"]
]
So, I think you're not pointing your models correctly.
Template:
<tr v-for="(row, idx1) in items">
<td class="table-success" v-for="(col, idx2) in row">
<input v-model="items[idx1][idx2]" type="text" />
</td>
</tr>
Script:
data () {
return {
items:[
["john","Micheal"],
["john","Micheal"],
["john","Micheal"],
["john","Micheal"]
];
};
}
Here's a working fiddle of it

Vue JS 2: Bind computed property to data attribute

I have a data object in Vue.js 2 that looks like this:
data: {
items: [
{
value1: 10,
value2: 10,
valuesum: ""
},
{
value1: 10,
value2: 100,
valuesum: "",
}
]
I render that data object in a table and run calculations on it. I want the valuesum property to be computed and stored in each object somehow. In other words, I want the code to essentially perform this:
data: {
items: [
{
value1: 10,
value2: 10,
valuesum: {{ value1 + value2 }} //20
},
{
value1: 10,
value2: 100,
valuesum: {{ value1 + value2 }} //110
}
]
The computed attribute doesn't seem to be able to accomplish this. I tried to use the following function but this does not work:
function (index) {
for (let i = 0; i < this.items.length; i++ ){
return this.items[index].value1 + this.items[index].value2;
}
}
The closest I have managed to get to an answer is by doing the calculation inline, but I can't bind its result to the items.total object. My HTML looks like this:
<table id="table">
<thead>
<tr>
<td>Value 1</td>
<td>Value 2</td>
<td>Sum</td>
</tr>
</thead>
<tbody>
<tr v-for="item in items">
<td><input type="number" v-model="item.value1"></td>
<td><input type="number" v-model="item.value2"></td>
<td> {{ item.value1 + item.value2 }} </td>
</tr>
</tbody>
</table>
But I can't add v-model to it, since it's not an input. I'd like to avoid adding a readonly <input> to the column, since that doesn't seem like the best solution and isn't very elegant.
Here are a few approaches: Binding to a method, binding to a computed property, and binding to a data property that is saved during the computed property call:
<table id="table">
<thead>
<tr>
<td>Value 1</td>
<td>Value 2</td>
<td>Sum</td>
<td>Sum</td>
<td>Sum</td>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items">
<td><input type="number" v-model="item.value1"></td>
<td><input type="number" v-model="item.value2"></td>
<td> {{ sum(item) }} </td><!-- method -->
<td> {{ sums[index] }}</td><!-- computed -->
<td> {{ item.valuesum }}</td><!-- data property via computed -->
</tr>
</tbody>
</table>
The script:
var vm = new Vue({
el: "#table",
data: function () {
return {
items: [
{
value1: 10,
value2: 10,
valuesum: 0
},{
value1: 10,
value2: 100,
valuesum: 0,
}
]
}
},
computed: {
sums: function () {
var val = [];
for (var index in this.items) {
var sum = this.sum(this.items[index]);
val.push(sum);
// Update the local data if you want
this.items[index].valuesum = sum;
}
return val;
}
},
methods: {
sum: function (item) {
// Alternate, if you take valuesum out:
// for (var prop in item) {
// val += parseInt(item[prop]);
// }
return parseInt(item.value1) + parseInt(item.value2);
}
}
});
Is that the sort of thing you're looking for?

Displaying json object details in knockout js

I have the following fiddle where I am trying to display the data in key:value pairs,
i.e., key as header and followed by the information as rows .
I have the data in this format:
self.data = ko.observableArray([{
1:
{
name: 'Name 1',
lastLogin: '8/5/2012'
}
}
, {
2:
{
name: 'Name 2',
lastLogin: '2/8/2013'
}
}
]);
I have fiddle as :
https://jsfiddle.net/1988/z7nnf0fh/1/
I am expecting as:
1
name Name 1 lastLogin 8/5/2012
2
name Name 2 lastLogin 2/8/2013
I'd personally move all logic to your viewmodel. Then you could either use ko.toJSON to stringify the contents of each object or if you really want to have the output like above, you could do:
function DataModel() {
var self = this;
self.data = ko.observableArray([{
1: {
name: 'Name 1',
lastLogin: '8/5/2012'
}
}, {
2: {
name: 'Name 2',
lastLogin: '2/8/2013'
}
}
]);
self.formattedValues = ko.observableArray([]);
self.formatData = function() {
var tempRow = [];
ko.utils.arrayForEach(self.data(), function(item) {
for (var i in item) {
for (var j in item[i]) {
tempRow.push({
key: j,
value: item[i][j]
});
}
self.formattedValues.push({
key: i,
rows: tempRow
});
tempRow = [];
}
})
};
self.formatData();
}
var dataModel = new DataModel();
ko.applyBindings(dataModel);
.name {
color: #bbb;
}
.value {
fot-weight: bold
}
th {
width: 25px;
}
p {
margin-right: 10px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="template: { name: 'template', data: formattedValues }"></div>
<script type="text/html" id="template">
<table>
<tbody data-bind="foreach: $data">
<tr>
<td data-bind="text: key"></td>
</tr>
<tr>
<td data-bind="foreach: rows">
<p>
<span class="name" data-bind="text: key + ': '"></span>
<span class="value" data-bind="text: value"></span>
</p>
</td>
</tr>
</tbody>
</table>
</script>
Hope that helps in some way

Applying a filter on each column of the dynamic table in AngularJS

I am trying to create a general table using element type custom directive that takes collection of data and generates the table header and create all the rows and columns of the table, then i tried to sort all the columns. The part of this code is working fine. But my next goal is to apply the filter on all the columns of the table, as the data is dynamic so we cannot decide about the field to filter at run time. The problem I diagnosed is that I am using ng-repeat="row in customers|filter:{$scope.searchkey:$scope.search}". Here seems to be the problem because in then expression the first thing should be object but $scope returns object.
Following is my code.
Index.html
<body>
<div>
<my-table input="Customers"></my-table>
<br />
<br />
<br />
<my-table input="Users"></my-table>
</div>
</body>
script.js
angular.module('DirectiveDemo', [])
.controller('Controller', ['$scope', function ($scope) {
$scope.Customers = [{ Name: "2Touqeer", Code: "2" },
{ Name: "3Nadeem", Code: "3" },
{ Name: "1Talha", Code: "1" },
{ Name: "4Muslim Khan", Code: "4" }
];
$scope.Users = [{ Name: "Touqeer", Code: "2", ID: "2Touqeer", CID: "CID1" },
{ Name: "Nadeem", Code: "3", ID: "3Muslim", CID: "CID3" },
{ Name: "Talha", Code: "1", ID: "1Nadeem", CID: "CID2" },
{ Name: "Muslim Khan", Code: "4", ID: "1Talha", CID: "CID5" },
{ Name: "Khan", Code: "4", ID: "1Khan", CID: "CID78" }
];
}])
.directive('myTable', function () {
return {
restrict: 'E',
transclude: true,
scope: {
customerInfo: '=input'
},
templateUrl: 'my-table-info.html',
controller: function ($scope) {
$scope.searchKey = 'CID';
alert($scope.searchKey)
$scope.reverseSort = false;
$scope.search = '';
$scope.List = [];
$scope.order = function (item) {
$scope.orderByField = item;
alert($scope.search)
}
$scope.filterValue = function (itemKey,valueKey) {
$scope.searchKey = itemKey;
if (valueKey != 'undefined') {
$scope.search = valueKey;
alert($scope.search)
}
}
}
};
})
my-table-info.html
<table ng-transclude>
<thead class="GridHeaderItem ControlBorder">
<tr>
<th ng-repeat="(key, value) in customerInfo[0]"> <a href="#" ng-click="order(key); reverseSort = !reverseSort">
{{key}}
<span ng-show="orderByField==key">
<span ng-show="!reverseSort">
<i class="glyphicon-circle-arrow-up glyphicon"></i>
</span>
<span ng-show="reverseSort">
<i class="glyphicon-circle-arrow-down glyphicon"></i>
</span></span>
</a></th>
</tr>
<tr class="ControlBorderRight ControlBorderTop ControlBorderBottom">
<td class=" ControlBorderLeft ControlBorderBottom" ng-repeat="(key, value) in customerInfo[0]" >
<input type="text" style="width:100%;" ng-model="searchfilter" ng-change="filterValue(key,searchfilter);" />
<!--ng-change="filter(key);"-->
</td>
</tr>
</thead>
<tr ng-repeat="row in customerInfo|filter:{co[row]:2}|orderBy:orderByField:reverseSort" class="ControlBorderRight ControlBorderTop ControlBorderBottom ">
<td ng-repeat="col in row" class=" ControlBorderBottom ControlBorderLeft Control LabelControl">{{col}}</td>
</tr>
</table>
You should build a custom filter function angular.module('myMod',[]).filter('myFilter',function(){ return function(input){...} }) then your repeat should look like this: ng-repeat="row in customers | myFilter" - the row object will be fed to the filter function as the input parameter.

Categories