TrtG
TrtG

Reputation: 2848

Add html content after directive template

Having this HTML :

<div messages>
     Some content...
</div>

This directive :

myAppDirectives.directive("messages", function () {
    return {
        restrict: 'A',
        templateUrl: '/directives/messages/messages.html',
        link: function (scope, elem, attrs) {
            //...
        }
    };
});

And messages.html :

<p>message1</p>
<p>message2</p>

The content of my html gets replaced by the directive template but i'd like it to just be appended.

Html becomes this :

<div messages>
    <p>message1</p>
    <p>message2</p>
</div>

But I'd like this :

<div messages>
    <p>message1</p>
    <p>message2</p>
    Some content...
</div>

Is this possible without using ng-include?

Upvotes: 0

Views: 44

Answers (2)

MattDionis
MattDionis

Reputation: 3616

This looks like a perfect situation to use ngTransclude. Try:

myAppDirectives.directive("messages", function () {
    return {
        restrict: 'A',
        transclude: true,
        templateUrl: '/directives/messages/messages.html',
        link: function (scope, elem, attrs) {
            //...
        }
    };
});

messages.html:

<p>message1</p>
<p>message2</p>
<ng-transclude></ng-transclude>

Upvotes: 2

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40328

If you really want this behaviour, use transclusion:

myAppDirectives.directive("messages", function () {
    return {
        restrict: 'A',
        transclude: true,
        templateUrl: '/directives/messages/messages.html',
        link: function (scope, elem, attrs) {
            //...
        }
    };
});

And the template becomes:

<p>message1</p>
<p>message2</p>
<span ng-transclude></span>

The original content of the <div messages> element will be wrapped in the <span ng-transclude>, but this should not harm.

Upvotes: 1

Related Questions