3

我有一个myList指令,它包含了它的内容。当我尝试将一个<my-list>元素嵌套在另一个<my-list>.

JS 小提琴:http: //jsfiddle.net/fqj5svhn/

指令:

var MyListDirective = (function () {
    function MyListDirective() {
        this.restrict = 'E';
        this.replace = true;
        this.transclude = true;
        this.scope = {
            myListType: '='
        };
        this.controller = function () {
            this.classes = 'my-class';
        };
        this.controllerAs = 'myList';
        this.bindToController = true;
        this.template = '<ul ng-class="myList.classes" ng-transclude></ul>';
    }
    return MyListDirective;
})();
angular.module('myApp', []).directive('myList', function () {
    return new MyListDirective();
});

该指令的示例用法:

<div ng-app="myApp">
    <my-list my-list-type="'someType'">
        <li>foo</li>
        <li>bar</li>
        <li>
            <my-list my-list-type="'anotherType'">
                <li>cats</li>
                <li>dogs</li>
            </my-list>
        </li>
    </my-list>
</div>

渲染的内容:

<div ng-app="myApp" class="ng-scope">
    <ul ng-class="myList.classes" ng-transclude="" my-list-type="'someType'" class="ng-isolate-scope my-class">
        <li class="ng-scope">foo</li>
        <li class="ng-scope">bar</li>
        <li class="ng-scope">
            <ul ng-class="myList.classes" ng-transclude="" my-list-type="'anotherType'" class="ng-isolate-scope my-class">
            </ul>
        </li>
        <li class="ng-scope">cats</li>
        <li class="ng-scope">dogs</li>
    </ul>
</div>

如您所见,内部的列表项myList似乎被外部嵌入myList。我想要发生的事情:

<div ng-app="myApp" class="ng-scope">
    <ul ng-class="myList.classes" ng-transclude="" my-list-type="'someType'" class="ng-isolate-scope my-class">
        <li class="ng-scope">foo</li>
        <li class="ng-scope">bar</li>
        <li class="ng-scope">
            <ul ng-class="myList.classes" ng-transclude="" my-list-type="'anotherType'" class="ng-isolate-scope my-class">
                <li class="ng-scope">cats</li>
                <li class="ng-scope">dogs</li>
            </ul>
        </li>
    </ul>
</div>

建议?

4

1 回答 1

2

发生这种情况是因为当浏览器呈现它期望<li>在里面的页面时<ul>,但是你的情况是它在里面<my-list>是一个无效的标记。所有这些事情都发生在 Angular 引导和运行指令之前。您无法预测浏览器在标记无效时将如何解释您的标记,在这种特殊情况下,它会将<li>' 推到一起。

在这个小提琴中,我已经替换了<ul>and <li><div>它对嵌套没有任何要求,并且嵌入工作得很好。

于 2015-06-29T09:31:03.560 回答