How to write an AngularJS directive that creates DOM elements that are other directives?

痞子三分冷 提交于 2019-12-08 08:14:50

问题


I'm writing some pretty complex DOM manipulations, which is sure to test my ability to write very complex directives. I have not come across any examples (I think anyway) that demonstrate what I'd like to do.

Let's say I have a list of widgets, which can be of different types. These widgets need to be displayed within an <ul> element. Each type of widget can be different though, so the actual markup for each widget inside the <li> will drastically be different.

If all I needed was standard markup, I don't think it would be that difficult to implement this, but each of these widgets will in turn have to create html fragments that I want Angular to process. They could be something simple like wanting to use ng-click, but maybe something more complex like wanting to use my own custom directive too.

Ideally, I'd want to create directives for each of the widgets separately, just to separate concerns because I think the code for most of them will be quite complex in of themselves. Then, I'd probably want to have another directive check the type of the widget and create an html fragment that uses the individual widget directives. Does that make sense? If not, then I'd probably want to separate concerns in a similar way.

Is there a way to do this?


回答1:


Although the problem is open to different solution, the strategy you suggest with a "super directive" which is responsible for creating the widgets, contained in some data structure, seems reasonable. As I already said in a comment, I don't see any fundamental problem with this, although streamlining it could be a challenge.

In order to illustrate the basic idea with some working code, using $compile, see this fiddle.

Assuming a scope-bound data structure

$scope.widgets = [
    {directive: 'widget-directive-one'},
    {directive: 'widget-directive-two'},
];

with template

<ul>
    <li ng-repeat="widget in widgets" super-directive="{{ widget.directive }}"></li>
</ul>

The "super directive" could compile the directives given to it like so:

angular.module('myApp').directive('superDirective', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {

            // Create an element of the correct type
            var widgetElement = document.createElement(attrs.superDirective);

            // Possibly modify widgetElement here

            // Compile the element and append it to the LI element
            elem.append($compile(widgetElement)(scope));
        }
    };
});

See this directive as a proof of concept. It will probably need a lot of work to function as you want, much of it depending on design choices.



来源:https://stackoverflow.com/questions/22107048/how-to-write-an-angularjs-directive-that-creates-dom-elements-that-are-other-dir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!