简体   繁体   中英

JS object to HTML data binding with Knockout JS

I have a JS object constructed from XML.

How do I bind that JS object to html?

Example: ViewModel:

  vm: {
    a: ko.observable()
  }

JS (of the model):

aObj : {
  item1: [ { n: 'a1', v: 'v1'}, { n:'a2', v:'v2' } ],
  item2: [ ]
}

JS (binding logic):

vm.a(aObj);

HTML:

<div data-bind="with: vm.a">
  <div data-bind="foreach: item1">
     <div data-bind="text: n"></div>
  </div>
</div>

I cannot loop over the array elements of item1

What am I doing wrong? I just get the following computed DOM:

<div data-bind="with: vm.a">
  <div data-bind="foreach: item1">
  </div>
</div>

Seems to be working: http://jsfiddle.net/tpLVC/2/ .

Do you get any errors in the console? In the html in the fiddle, notice that the with binding is with: a . If your top level viewModel has the a property, then you should use it like this.

If you have a top level viewModel with a vm property, only then will the with: vm.a work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM