angularjsangularjs-compileangularjs-componentsangularjs-1.5

Angular $compile for dynamic content


Using Angular 1.5, I want to use a generic "overlay" component to display other components within a modal. I'd like to pass in other components to be rendered within the overlay.

I thought I could use $compile in my controller, but the component does not render:

In my controller:

ctrl.appendComponent = function(component_type) {
    ctrl.$content.empty(); // this is the overlay element
    var component = '<' + component_type + '></' + component_type + '>';
    ctrl.$content.append($compile(component)($scope));
};

I've created the component I want to pass in, for example "foo" and get only an empty element in the DOM:

<foo></foo>

Even though, in the template for foo component, I have:

<h1>header</h1>
<p>body</p>

And expect to see:

<foo>
  <h1>header</h1>
  <p>body</p>
</foo>

Solution

  • Here is an example, but it looks like you are doing the same thing. I would suggest simplifying your code, it may be the case that something is not returning what you think it is.

                    link: function(scope, iElem, tAttrs){
                                var html = "<div>hello</div>";
    
                                var content = $compile(html)(scope);
                                iElem.append(content);
                    }