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
-listener for the star icon in the header. Here is some code I used by now:
$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
}
});
}
});
};
The $scope.showFavorites
is just a variable containing true
or false
. I switch it's value when I ng-click
the star icon. It's initially initialized with false
:
$scope.showFavoriteOnly = function () {
$scope.showFavorites = !$scope.showFavorites;
};
A little problem is to no use the smart search, because the both icons (full star and empty star) differentiate only by a letter: fa-star
and fa-star-o
.
The .search
function has been taken from https://stackoverflow.com/a/23931504/3402092.
Little Edit: I marked the column as search type string:
DTColumnDefBuilder.newColumnDef(0).withOption('orderDataType', 'fa-classes').withOption('sType', 'string')
So I can use the search-input to find fa-star-o
.
I my case the data[index] was empty (don't really know why). But I managed to get it working with following function:
I replaced
data
withrowData
and managed to access the html-object.The desired functionality is shown here: plnkr.co/edit/PRu8bZI0vO1ocgvjW9oA?p=preview
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 withfa-star
/fa-star-o
this way :Here invoked by a button click
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 afa-star
icon.