简体   繁体   中英

Angular - dynamic component generation

I'm looking to get an architectural question answered and doing so through the context of using a modal as an example. So for starters, please don't answer this question with "use bootstrap's modal service".

Basically, I want to know what the "Angular way" is around the case when one needs html to appear out of thin air, and apply components or directives to it. A data request error modal is a good example: if for instance, a component tries to load some kind of data, and the data comes back with some kind of error, I want the data service to be able to trigger a modal programmatically.

This begs the question: where does the template go, in this case? Unless I'm mistaken, a directive won't be compiled for markup that isn't on the page, which from an architectural standpoint is desirable (eg I don't want code on the page that is unlikely to be used, like in the case of an error modal which isn't terribly common). A service would have to be attached to a controller, which, same case, won't be added unless I have the markup on the page.

What is the pattern, then, for activating a component that is essentially (and in my opinion, desirably so) non-existent when the page loads? I'd ideally prefer the modal component to be ignored entirely until the user experience requires it. So far, ng-if statements, via including a single div somewhere on the page, seem the best approach. But even that is technically "messy", since you're adding markup to the page that is supporting only a "potential" case.

It'd be nice to be able to, from some service or controller or directive, broadcast a "triggerErrorModal" event, pass it some arguments, and have the application spin up the modal component. Note, there are other cases where this could work, so think of this as a more general question.

Thoughts?

I know you have said that you don't want to just be sent to bootstrap's modal service.. However.. looking into the source code gives a lot of information about how to do this.

Basically you can add an HTML element using:

var el = angular.element('<div class="new-thing"><my-directive></my-directive></div>')

Add it to the page:

var body = $document.find('body').eq(0);
body.append(el)

And then compile it by:

var compiled = $compile(el)($scope);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM