Frage

I've directives container and item.

directive('container', function(){
    return {
        replace: true,
        template: "<div>contains <p>...</p> </div>'
    }
});


directive('item', function(){
    return {
        replace: true,
        template: "item"
    }
});

They are supposed to be used like this:

<container>
    <item>
    <item>
    <item>
</container>

Expected output html:

<div>contains <p>item item item </p> </div>

How to take item directives from container content and render them as repeatable directive in place of ... at container template?

War es hilfreich?

Lösung

Since directive templates must have exactly one html root element, template: "item" is not valid. It has to be at least something like template: '<span>item</span>', which produces:

<div>
    contains 
    <p>
        <span>item</span>
        <span>item</span>
        <span>item</span>
    </p>
</div>

The two directives are:

app.directive('container', function() {
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    template: '<div>contains <p ng-transclude></p></div>'
  };
});

app.directive('item', function() {
  return {
    restrict: 'E',
    replace: true,
    template: '<span>item</span>'
  };
});

plunker

Andere Tipps

Use the transclude: true option :

directive('container', function(){
    return {
        replace: true,
        transclude: true,
        template: "<div>contains <p ng-transculde></p> </div>'
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top