Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js $compile returns array of html but not actual html

I have the following code:

app.directive('mySample', function($compile) {
    return {
        //template:"<input type='text' ng=model='sampleData'/> {{sampleData}} <br/>"
        link: function(scope, element, atts, controller) {
            var markup = "<input type='text' ng=model='sampleData'/> {{sampleData}} <br/>";  
            angular.element(element).html($compile(markup)(scope));
            console.log($compile(markup)(scope));
        }
    };
});

And I would expect it to generate an input, some span that's coupled via the scope and a break. However I get this output:

[[object HTMLInputElement], [object HTMLSpanElement], [object HTMLBRElement]]

I also tried the template, in comment here, separately and then commenting out the link part. That generates the input and break elements but not the span that shows the coupled model input sampleData.

I have a non-working sample at http://jsfiddle.net/KvdM/nwbsT/ that demonstrates it.

like image 490
Kris van der Mast Avatar asked Jul 26 '13 13:07

Kris van der Mast


2 Answers

Try this:

element.html(markup);
$compile(element.contents())(scope);
like image 57
AlwaysALearner Avatar answered Oct 22 '22 00:10

AlwaysALearner


Running the function returned by the $compile service gives you DOM elements rather than html. So you need to insert them into your page using append (or equivalent):

angular.element(element).append($compile(markup)(scope));
like image 10
Derek Ekins Avatar answered Oct 22 '22 01:10

Derek Ekins