Use get_permalink
(which returns the URL) instead of the_permalink
(which prints the URL).
Try:
foreach ( $categories as $category ) {
$link = get_term_link( $category );
$html .= "<li><a href="https://wordpress.stackexchange.com/questions/159187/{$link}" data-filter="{$category->category_nicename}">{$category->cat_name}</a></li>";
}