Search code examples
jqueryhtmlangularjsangularjs-directivelive

Attach AngularJS directives to live content from jQuery.html()


I've run into an issue where I've much to my dismay had to use update a view via jQueries .html function, so effectively looks like

$('#directory-view').html( response.html );

This adds items to a table, the markup is as follows

<tr data-marked="0" id="file-49" data-id="49" data-folder="0" data-readonly="0">

            <td width="30">
                <span class="action file"></span>
            </td>

            <td class="filename">
                readme.txt
            </td>

            <td width="200" class="uk-text-center">
                text/plain
            </td>

            <td width="200" class="uk-text-center">
                <span data-uk-tooltip title="15/05/2015 11:17:53">8 minutes ago</span>
            </td>

            <td width="100" class="uk-text-center">
                Owen
            </td>

</tr>

Then I've got my AngularJS Directive as follows

App.directive('marked', function(){
    return {
        restrict: 'A',
        link: function($scope, element, attrs){

            /* Toggle the marked state of a table row */
            element.on('click', function(e){
                var marked = element.attr("data-marked") == "1" ? "0" : "1";
                element.attr("data-marked", marked);
                $(document).trigger('marked');
            });

            /* If the url contains a file-34 it will
            automatically scroll to it and mark it as selected */
            if( window.location.hash && element.attr('data-marked') == "0" ){
                $(window.location.hash).trigger('click');
            }
        }
    };
});

However the issue that I'm having is, that angular isn't detecting new table content so isnt attaching the directive to the new items.

I tried my luck with this but it isn't working

$scope.$apply(function(){
    $('#directory-view').html( response.html );
});

Could somebody point me in the direction as to make angular check for new items and hookup the directives again please.

Many thanks


Solution

  • You will need to use the compile service on the new html

    var element = $compile(response.html)($scope);
    $('#directory-view').html(element);