Pass to the DOM strings with HTML and render it.
I'm extending properties of an observable (with KnockoutJS) using the follow syntax:
self.showDetails.subscribe(function (context) {
var details = this.showDetails();
details.nameWithCnpj = context.name() + " <small>" + context.cnpj() + "</small>";
}, this);
If you pay attention on the following line, you can see the HTML on it:
details.nameWithCnpj = context.name() + " <small>" + context.cnpj() + "</small>";
When the <small></small>
tag arrives on the HTML, it is rendered as string instead of vanilla HTML.
The container that houses the nameWithCnpj
(using KnockoutJS) is the following:
<h2 class="bold float-left" data-bind="text: nameWithCnpj"></h2>
So I ask: How can I teach to JavaScript (or HTML) that the nameWithCnpj
variable should be a DOM element instead of a simple string?
You need to use the html
binding instead of text
:
The html binding causes the associated DOM element to display the HTML specified by your parameter.
Typically this is useful when values in your view model are actually strings of HTML markup that you want to render.
So change your view to:
<h2 class="bold float-left" data-bind="html: nameWithCnpj"></h2>
If you want to be more MVVM you can create a template which encapsulates your formatting logic and use the template
binding:
<h2 class="bold float-left"
data-bind="template: { name: 'nameWithCnpj', data: showDetails}"></h2>
<script id="nameWithCnpj" type="text/html">
<span data-bind="text: name"></span>
<small data-bind="text: cpnj"></small>
</script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments