0

Here is my html looks like:

<div class="xyz-template" data-bind="html:myViewModel().htmlTemplate"></div>

And I would like to have data-bind in htmlTemplate itself: here is my knockout:

function myViewModel() {
    self.htmlTemplate = ko.observable();
    self.initialize = function ()
 {
        self.htmlTemplate(`
          <p data-deId="de-box-5" data-bind="html: myViewModel().getDynamicContent()">
            Initial content
          </p>
        `);
 };

self.getDynamicContent = function()
{
   return "dynamic content";
};

};

Well the return value is

Initial content

How can I have inner bind in binding html?

Saeid
  • 13,224
  • 32
  • 107
  • 173
  • Does this answer your question? [Knockout: Best Way To Create Links In Rendered Content Bound To ViewModel Functions](https://stackoverflow.com/questions/34618257/knockout-best-way-to-create-links-in-rendered-content-bound-to-viewmodel-functi) – Jason Spake Nov 22 '22 at 16:34

1 Answers1

0

Whole trick is around rebinding your view. ko does not allow to call applyBindings twice on the same node, so you need to cleanNode from bindings and apply it to element.

Here is the working scenario:

function myViewModel() {
  let self = this
  
  self.htmlTemplate = ko.observable();
  self.initialize = function ()
  {
        self.htmlTemplate(`
          <p data-deId="de-box-5" data-bind="html: myViewModel().getDynamicContent()">
            Initial content
          </p>
        `);
  };

  self.getDynamicContent = function()
  {
     return "dynamic content";
  };

  return self;
};

const vm = myViewModel();
const root = $('.xyz-template');

ko.applyBindings(vm, root[0]);
vm.initialize();

const templateHolder = root.find('p');
ko.cleanNode(templateHolder[0]);
ko.applyBindings(vm, templateHolder[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div class="xyz-template" data-bind="html: htmlTemplate"></div>

Keep in mind that in your particular case you cannot rebind root because everytime you initialize binding html binding from xyz div kicks in, so again <p> is somehow detached

Here you will also find better ways to solve that problem knockout custom html binding

Code which I posted is just to show the concept

jgasiorowski
  • 1,033
  • 10
  • 20