0

How can i render the html that is in encoded state using the html binding?. Currently with what i have, it just gives me the text rather than the rendered html. http://jsbin.com/wudopeseloya/1/edit

var ViewModel = function() {
    this.myHtml = "<h1>hello</h1>";
};

ko.applyBindings(new ViewModel()); 

and

<div data-bind="html:myHtml"></div>
user1415567
  • 431
  • 5
  • 14

1 Answers1

4

First determine how you want to decode html strings. There are a bunch of options listed here: HTML Entity Decode

Assuming you have a global function called decodeEntities available, you can provide a computed property that simply performs this decoding over myHtml.

var ViewModel = function() {
    this.myHtml = "&lt;h1&gt;hello&lt;/h1&gt;";
    this.decodedHtml = ko.computed(function(){
        return decodeEntities(this.myHtml);
    });
};

Please be aware that since myHtml is not an observable, decodedHtml will always resolve to the same value and never trigger updates (unless manually enforced), no matter what value you assign to myHtml afterwards.

Alternative ways of achieving the same results are to either decode myHtml inline or create a custom binding that does decoding on the spot.

Community
  • 1
  • 1
Polity
  • 14,734
  • 2
  • 40
  • 40
  • As you already observed, this.myHtml is not an observable. Therefore it makes no sense to make this.decodedHtml a computed observable. You can just as well say `this.decodedHtml = decodeEntities(this.myHtml);` – Hans Roerdinkholder Aug 15 '14 at 09:28
  • 1
    @Hans yes that is correct, i used the decodeEntities and used it inline while rendering the html so that i don't have to create another variable to hold the decoded value. http://jsbin.com/wudopeseloya/3/edit . Also thank you so much guys for all the help. – user1415567 Aug 15 '14 at 15:44