Angularjs 使用ng repeat向页面添加指令

Angularjs 使用ng repeat向页面添加指令,angularjs,angularjs-directive,angularjs-ng-repeat,ng-repeat,Angularjs,Angularjs Directive,Angularjs Ng Repeat,Ng Repeat,我正在尝试使用ng repeat向页面添加指令。基本上我想做一些事情,比如: <{{ currentDirective.directiveName }} ng-repeat="currentDirective in directiveList" /> 下面是一个我在上下文中尝试做的示例 为什么要这样添加指令?根据您的示例,您返回的指令不同吗?不确定你到底想完成什么,但正确的方法是 <div my-directive ng-repeat="i in item" />

我正在尝试使用ng repeat向页面添加指令。基本上我想做一些事情,比如:

<{{ currentDirective.directiveName }} ng-repeat="currentDirective in directiveList" />

下面是一个我在上下文中尝试做的示例


为什么要这样添加指令?根据您的示例,您返回的指令不同吗?不确定你到底想完成什么,但正确的方法是

<div my-directive ng-repeat="i in item" />


该指令的控制器或链接函数中会有逻辑

我用一个名为
bind compiled html
的指令解决了这个问题:

指令代码:

function bindCompiledHtml($compile) {
    return {
        restrict: 'A',
        link: function($scope, $element, $attrs) {
            var html = $scope.$eval($attrs.bindCompiledHtml),
                toCompile = angular.element(html);
            $element.append($compile(toCompile)($scope));
        }
    };
}
用法:

<div ng-repeat="directive in directiveHtmlList"
    bind-compiled-html="directive.directiveHtml">
</div>

更多信息,请查看Angular docs on(绑定编译html的灵感)和。

没有一种方法(据我所知)以这种方式动态生成指令;您有一个
$compile
和一个
$digest
,两者都依赖于另一个。可以使用外部指令并根据ng repeat值返回模板。嘿,所以我尝试动态更改页面上的指令。我知道我可以在添加或删除指令后重新编译页面,但由于ng repeat处理对其呈现的集合的更改,我想也许我可以使用指令集合来完成。但这可能不可能。嘿,你发布的JSFIDLE不起作用。不过谢谢你提供的信息,我明天会调查这件事并处理一下。科迪,我编辑了我的答案。你说得对,小提琴坏了。请参见答案中的更新。基本上,HTML被正确地添加到DOM中,但Angular对此一无所知;由于HTML是动态添加的,Angular没有在其上运行$compile。在这种情况下,您需要手动或通过新的自定义指令(可能是
绑定并编译html
)运行$compile。新提琴的作品。。。但我仍然不推荐这种方法。嘿,我实际上有一个版本使用了compile,并且试图看看是否有一种方法可以做到这一点,同时仍然使用指令。我想看起来我不能。谢谢你的帮助,你的回答帮助我更好地理解了这件事:)科迪-看看。我一直在玩弄小提琴,想出了一个更干净的解决办法。它仍然使用$compile,但是所有的丑陋都像我建议的那样被封装在一个指令中。我将把它作为编辑贴在答案的底部。太棒了,非常感谢,我真的很感激。我认为bind编译的html将适用于我正在尝试的工作。这比我使用$compile时要简洁得多。
<div class="ng-scope ng-binding"
    ng-repeat="directive in directiveHtmlList"
    bind-compiled-html="directive.directiveHtml">
    <first-directive></first-directive>
</div>
<div class="ng-scope ng-binding"
    ng-repeat="directive in directiveHtmlList"
    bind-compiled-html="directive.directiveHtml">
    <second-directive></second-directive>
</div>