user5260143
user5260143

Reputation: 1098

Knockout- foreach over nested array- not working

I have observableArray which its elements- are arrays. I need over by foreach, but I need to show each time only the last element of the observableArray- i.e.- the last array. For example: My observable array is:

 self.treeLists = [
         [{id:1, name:'tar'}, {id:9, name:'se'}, {id:5, name:'tzav'}],
         [{id:4, name:'sus'}, {id:8, name:'par'}],
         [{id:7, name:'tal'}, {id:6, name:'med'}]
];

So I need to show only the third array- [{id:7, name:'tal'}, {id:6, name:'med'}]

Here is My HTML, but it cause problem!!! It read it like I tried to over on the observalbeArray and show its elements...

    <div data-bind="if: treeLists().length>1">
                    <div data-bind="foreach: treeLists()[treeLists().length-1]">
                        <div class="col-md-2">
                            <div class="organizationTreeItem">
                                <img class="floutR" data-bind="attr: {src: $parent.global.imagesManager.plusblue}, click:$parent.itemClickPathMode" />
                                <span data-bind="text:$data.name"></span>
                            </div>
                        </div>
                    </div>
                </div>

The error-message is:

Unhandled exception at line 1981, column 17 in http://localhost/myProj/Scripts/knockout-2.3.0.debug.js 0x800a1391 - JavaScript runtime error: 'OrgName' is undefined

You can see the situation when I debugged, see the picture:

enter image description here

Upvotes: 0

Views: 205

Answers (1)

Philip Bijker
Philip Bijker

Reputation: 5115

$data contains the objects of the last array, for example: {id:7, name:'tal'}

In HTML you're binding to $data.OrgName, but OrgName is not a member of the bound object, so it indeed is undefined, like the exception mentions. Did you mean to bind to "name"?

<span data-bind="text:name"></span>

Also treeLists is not an observableArray yet. Have a look at the following fiddle.

Upvotes: 1

Related Questions