2016-04-12 9 views
2

Ist es möglich, berechnete Werte an das zugrunde liegende Modell zu binden, so dass .rows().data() die Spalten c im folgenden Ausschnitt enthält?Berechnete Spaltenwerte mit Datenwerten verbinden Datenmodell

var data = [{ 
 
    a: 1, 
 
    b: 2 
 
}, { 
 
    a: 2, 
 
    b: 4 
 
}, { 
 
    a: 3, 
 
    b: 8 
 
}, { 
 
    a: 4, 
 
    b: 10 
 
}, ] 
 

 
var table = $('#dt').DataTable({ 
 
    data: data, 
 
    columns: [{ 
 
    title: "a", 
 
    data: "a" 
 
    }, { 
 
    title: "b", 
 
    data: "b" 
 
    }, { 
 
    title: "c", 
 
    data: null 
 
    }], 
 
    aoColumnDefs: [{ 
 
    aTargets: [2], 
 
    mRender: function(data, type, row) { 
 
     return row.a + row.b; 
 
    } 
 
    }] 
 

 
}); 
 

 
$('#log').click(function() { 
 
    var data = table.rows().data(); 
 
    // first row only 
 
    // logged -> {a: 1, b: 2} 
 
    // desired -> {a: 1, b: 2, c: 3} 
 
    console.log(data[0]); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<link href="https://cdn.datatables.net/1.10.11/css/jquery.dataTables.min.css" rel="stylesheet" /> 
 
<script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script> 
 

 

 
<table id="dt"> 
 
    <thead> 
 
    <tr></tr> 
 
    </thead> 
 
</table> 
 

 
<button id="log">Log Data</button>

Antwort

2

Sie können eine Funktion für columns.data Option definieren und zusätzliche Daten Eigenschaft c erstellen.

var table = $('#dt').DataTable({ 
    data: data, 
    columns: [{ 
    title: "a", 
    data: "a" 
    }, { 
    title: "b", 
    data: "b" 
    }, { 
    title: "c", 
    data: function(row, type, set, meta){    
     if(!row.hasOwnProperty('c')){ 
      row.c = row.a + row.b; 
     } 
     return row.c; 
    } 
    }] 
}); 

Code und Demonstration siehe this jsFiddle.

Verwandte Themen