Search code examples
angularjsangular-directive

TypeError: Cannot call method 'insertBefore' of null on $compile


I'm trying to build a recursive directive.

It looks like this:

var theTemplate = 
        '<span>{</span>' + 
            '<div>'+
                '<p>{{argVal}}</p>' +
                '<custom-args arg-val="argVal[0]"></custom-args>' +
            '</div>';

    return {
        restrict: "E",
        scope: {
            argVal: '='
        },
        controller: function($scope){
            //just some utilities
        },
        link: function(scope, element){
            element.html('').append(theTemplate);
            $compile(element.contents())(scope);
        }
    };      

Problem is, when I run it, I get:

Angularjs: TypeError: Cannot call method 'insertBefore' of null

What's the problem?


Solution

  • The problem was with

                element.html('').append(theTemplate);
                $compile(element.contents())(scope);
    

    Instead of appending the template to blank HTML, I needed to directly append it to the HTML like this

                element.html(theTemplate);
                $compile(element.contents())(scope);
    

    Now it works!