The nested transclude directive makes the internally relocated content in the wrong place

I have a directive myList

that passes its content. The problem occurs when I try to insert an element <my-list>

inside another <my-list>

.

JS Fiddle: http://jsfiddle.net/fqj5svhn/

Directive:

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

      

An example of using the directive:

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

      

What happens:

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

      

As you can see, the list items from the inner one myList

appear to be crisscrossing the outer one myList

. What I want:

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

      

Suggestions?

+3


source to share


1 answer


This is because when the browser renders the page, it expects to be <li>

inside <ul>

, but in your case, it is inside <my-list>

, which is invalid markup. It all happens before Angular bootstraps and runs directives. You cannot predict how the browser will interpret your markup when it is invalid, in this particular case it is pushing <li>

for sharing.



In this fiddle I have replaced <ul>

and <li>

with <div>

which has no requirements for nesting and the broadcast works just fine.

+2


source







All Articles