How can I generate on the fly directives in AngularJS?

折月煮酒 提交于 2020-01-13 04:26:27

问题


I want to be able to take an array of strings, and then create directives based upon those strings. Either element or attribute will work fine but can't seem to get it working.

<div ng-repeat="module in modules.directives">
    <div {{module.directive}}></div>
</div>

<div ng-repeat="module in modules.directives">
    <{{module.directive}}></{{module.directive}}>
</div>

<div ng-repeat="module in modules.directives">
    <{{module.directive}} />
</div>

Can't get any of these to work. Any ideas?


回答1:


You could define a directive that would proxy another directive like so

<div proxy="'ng-if'" proxy-value="'foo'"></div>
<div ng-init="n='ng-if'; v='foo';" proxy="n" proxy-value="v"></div>

that would both be equivalent to

<div ng-if="foo"></div>

the proxy directive definition would be

app.directive('proxy', function ($parse, $injector) {
    return function (scope, element, attrs) {
        var nameGetter = $parse(attrs.proxy);
        var name = nameGetter(scope);
        var value = undefined;
        if (attrs.proxyValue) {
          var valueGetter = $parse(attrs.proxyValue);
          value = valueGetter(scope);
        }
        var directive = $injector.get(name + 'Directive')[0];
        if (value !== undefined) {
            attrs[name] = value;
        }
        return directive.compile(element, attrs, null)(scope, element, attrs);
    };
});

This is actually kind of a fun directive to write once in a life. :-) but it lacks a lot of the native directive features (for instance template, templateUrl, controller, etc). All those features are available in the original Angular source code in a private function called applyDirectivesToNode, so it is easy to copy/paste some parts, but ugly... I have written a demo matching your usecase here.

Another solution, if you don't mind your proxied directive does not share the same element as the proxy directive's one, would be to $compile a dynamic template at runtime that you would include. Here is a demo.




回答2:


ng-include can help you. The approach would be to define a template for each of the directives. Something like this

<script type="text/ng-template" class="template" id="test-module">
<test-module></test-module>
</script>

Then in ng-repeat do

<div ng-repeat="module in modules.directives">
     <ng-include src="module.directive">
</div

If the template id matches with module.directive that directive would get rendered.



来源:https://stackoverflow.com/questions/18894403/how-can-i-generate-on-the-fly-directives-in-angularjs

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