怎样才能在AngularJS飞指令? [英] How can I generate on the fly directives in AngularJS?

查看:84
本文介绍了怎样才能在AngularJS飞指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够把字符串数组,然后创建基于这些字符串指令。无论是元素或属性将正常工作,但似乎无法得到它的工作。

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?

推荐答案

您可以定义一个指令,会的代理的另一个指令,像这样

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>

这既能相当于

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

代理指令定义是

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);
    };
});

这实际上是一种有趣的指令在生命写一次。 :-)但它缺乏大量的原生指令功能(比如模板 templateUrl 控制器的等)。所有这些功能都在原角源$ C ​​$ C提供所谓的私有函数 applyDirectivesToNode ,所以很容易复制/粘贴一些部分,但丑...我写了一个演示符合您的用例 rel=\"nofollow\">。

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.

这篇关于怎样才能在AngularJS飞指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆