3

我对 Angular 很陌生。尽管我已经取得了很大的进步,但仍有一些我不知道的事情。

目前我遇到了一个嵌入“问题”。

基本上,我们想要的是用父指令控制的 html 分别包装每个嵌入的元素/指令。

例子:

<my:directive>
    <my:sub-directive>Child 1</my:sub-directive>
    <my:sub-directive>Child 2</my:sub-directive>
    <my:sub-directive>Child 3</my:sub-directive>
</my:directive>

期望的结果(我保留了指令元素以使示例更加清晰):

<my:directive>
    <ul>
        <li>
            <div class="panel">
                <div class="header">
                    // Some stuff that's controlled by my:directive comes here
                </div>
                <div class="content">
                    <my:sub-directive>Child 1</my:sub-directive>
                </div>
            </div>
        </li>
        <li>
            <div class="panel">
                <div class="header">
                    // Some stuff that's controlled by my:directive comes here
                </div>
                <div class="content">
                    <my:sub-directive>Child 2</my:sub-directive>
                </div>
            </div>
        </li>
        <li>
            <div class="panel">
                <div class="header">
                    // Some stuff that's controlled by my:directive comes here
                </div>
                <div class="content">
                    <my:sub-directive>Child 3</my:sub-directive>
                </div>
            </div>
        </li>
    </ul>
</my:directive>

有谁知道如何处理这个问题?我知道在我的示例中我可以引入一个面板指令,但请注意这只是同一问题的一个示例。

4

1 回答 1

1

您可以将第五个参数传递给指令的链接函数transclude,然后在其中进行操作,这是一个简单的示例:

angular.directive('myDirective', function ($compile) {
    return {
        restrict:'EA',
        transclude:true,
        link: function (scope, elm, attrs,ctrl,transclude) {
            transclude(scope,function(clone) {
                //clone is an array of whatever is inside your main directive
                clone.filter('mySubDirective').each(function(index, value){
                    //create your html and you might have to $compile it before:
                    elm.append(myHtml);                    
                });
            });
        }
    };

})

于 2014-12-11T14:21:02.920 回答