How can I generate on the fly directives in AngularJS?

♀尐吖头ヾ 提交于 2019-12-04 14:03:33

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.

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.

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