I would like to filter datatable table by a attribute class name. Here is some image. The idea is, to click on the star icon near the table header to show only entries, which are favorite.
I already tried some options how to achieve this, but it doesn't work. As I understood, I should define some
keyup
$scope.dtInstanceCallback = function (dtInstance) {
var table = dtInstance.DataTable;
// Apply the search
table.columns().eq(0).each(function (colIdx) {
if ($('i', table.column(colIdx).header())[0] != undefined) {
$('i', table.column(colIdx).header()).on('keyup', function () {
if ($scope.showFavorites) {
table
.column(colIdx)
.search('fa-star', false, false, true)
.draw();
} else {
//here drop the search by the star value drop search
}
});
}
});
};
$scope.showFavorites
true
false
ng-click
false
$scope.showFavoriteOnly = function () {
$scope.showFavorites = !$scope.showFavorites;
};
fa-star
fa-star-o
.search
DTColumnDefBuilder.newColumnDef(0).withOption('orderDataType', 'fa-classes').withOption('sType', 'string')
fa-star-o
I have the feeling, that what you really are looking for is a custom filter. A custom filter is a customized search / filter that can be either dynamic (as a regular search) or permanent, which mean that subsequent searches will be a subset of that custom filter, until it is removed.
I imagine you have columns with content like <i class="fa fa-star-o"></i>
in the first column. You can implement two custom filters that filters out rows with fa-star
/ fa-star-o
this way :
$scope.starFilter = function() {
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
return $(data[0]).hasClass('fa-star')
}
)
$scope.dtInstance.DataTable.draw()
$.fn.dataTable.ext.search.pop() //remove this line to make the filter persistent
}
$scope.starOFilter = function() {
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
return $(data[0]).hasClass('fa-star-o')
}
)
$scope.dtInstance.DataTable.draw()
$.fn.dataTable.ext.search.pop() //remove this line to make the filter persistent
}
Here invoked by a button click
<button ng-click="starFilter()">star filter</button>
demo -> http://plnkr.co/edit/hUSZ0XpRDZPjERsr0vF5?p=preview
The very great advantage of this approach is that you can make the filter persistent. If you not pop()
the filter then subsequently user searches will be a subset of the filter subset itself, for example within "favorites", all rows with a fa-star
icon.