Reputation: 1175
Is there a way to add static HTML inside generated template?
I have that code:
<test></test>
<test></test>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
template:
'<div class="wrapper">' +
'<div class="content">' +
'</div>' +
'</div>'
};
});
</script>
... And then, I want to add <p>foo</p>
(see yellow note below) inside first <content>
, but not inside second. So, the output should be:
<test>
<div class="wrapper">
<div class="content">
foo
</div>
</div>
</test>
<test>
<div class="wrapper">
<div class="content">
</div>
</div>
</test>
How I can do it?
jsFiddle as aksed in the comments.
Note: This is just SO example. In the real code, it should be added more complex HTML markup, not simple
<p>foo</p>
. For example, it may be added something like:<div class="..."><p>...</p><p>...</p></div>
. Or, maybe, some HTML table. That is what I want.
Upvotes: 1
Views: 1333
Reputation: 7867
You can use ngTransclude here.
You would define your directive like this:
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
transclude: true,
template:
`<div class="wrapper">
<div class="content">
<ng-transclude></ng-transclude>
</div>
</div>`
};
});
Then in your HTML, you would have:
<test>
<p>foo</p>
</test>
<test></test>
And the <p>foo</p>
will be inserted automatically inside the ng-transclude
element in your template.
More information on AngularJS documentation.
Upvotes: 5
Reputation: 1431
This will solve your problem.
Directive
myApp.directive("test", function($compile) {
return {
restrict:'E',
link: function(scope, element, attrs) {
var childContent = '';
if(attrs.content == 'foo')
childContent = '<p>foo</p>';
var htmlText = '<div class="wrapper">' +
'<div class="content">' +
childContent+
'</div>' +
'</div>';
element.append($compile(htmlText)(scope));
}
};
});
Template
<test content='foo'></test>
<test></test>
Upvotes: 1
Reputation: 590
This is how I would do it. Assuming you already know what content to add for each directive.
<test content="foo"></test>
<test content=""></test>
<script>
var app = angular.module("myApp", []);
app.directive("test", function() {
return {
template: function(el, attrs){
'<div class="wrapper">' +
'<div class="content">' + '<p>'+attrs.content+'</p>'
'</div>' +
'</div>'
}
};
});
</script>
That would give you the desired output.
Upvotes: 0