角度包裹分开转换元素?

时间:2014-12-11 13:42:07

标签: angularjs angularjs-directive angularjs-ng-repeat transclusion angularjs-ng-transclude

我对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>

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

1 个答案:

答案 0 :(得分: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);                    
                });
            });
        }
    };

})