简体   繁体   中英

Knockout foreach not working

I have the following HTML:

<!-- ko.foreach: properties -->
<span data-bind="text: $data.Name"></span>
<span data-bind="text: $data.Age"></span>
<!-- /ko -->

And this javascript:

function MyViewModel() {
    var self = this;
    self.properties = ko.observableArray([
        {Name: "John", Age: 32},
        {Name: "Steve", Age: 23}
    ]);
}
ko.applyBindings(new MyViewModel());

Here's the jsfiddle http://jsfiddle.net/cFB5B/

Why doesn't the foreach work?

It's ko foreach , not ko.foreach when binding a foreach inside a HTML comment (Note 4) :

<!-- ko foreach: properties -->
<span data-bind="text: Name"></span>
<span data-bind="text: Age"></span>
<!-- /ko -->

http://jsfiddle.net/cFB5B/1/

Also, you don't need to use the $data, but that wasn't causing the problem.

You have a type . to much in the foreach declaration:

Instead

<!-- ko.foreach: properties -->

it should be

<!-- ko foreach: properties -->

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