Two array bindings in one foreach loop in JS knockout

Please see my model below:

viewModel = [ { StudentName : 'Ronald', Reviews : [ '3/5', '2/5', '4/5'], TeacherNames : [ 'Nema', 'Sarah', 'Vilson'] }, { StudentName : 'Chris', Reviews : [ '4.5/5', '2.5/5', '3.5/5'], TeacherNames : [ 'Nema', 'Sarah', 'Vilson'] } ] 

In the HTML below, I am trying to display overviews in a nested foreach structure. Reviews are displayed based on expectations. but how can I post TeacherNames with this single review? I put TeacherNames[$index] , but it does not work.

Note 1: The number of elements in the array (i.e. reviews and author names) will be the same.

Note 2: I do not want to change the structure of this JSON model, something like adding an additional variable and placing both parameters in one array.

 <div data-bind="foreach:viewModel"> <span data-bind="text: StudentName"></span> <ul data-bind="foreach:Reviews"> <li> <a href="#" data-bind="text:$data">Inbox </a> <span class="ui-li-count" data-bind="text:TeacherNames[$index]">123</span> </li> </ul> </div> 

Please check Fiddle .

+4
source share
4 answers

Think of it this way: $index is observable, and $index() is the value of observable. You need to specify the TeacherNames array, not the observable.

Using

<span data-bind="text:$parent.TeacherNames[$index()]" >123</span>

instead

<span data-bind="text:$parent.TeacherNames[$index]" >123</span>

to access the value of $index() .

I made a copy of your script with the changes .

Also, thanks to Calvin who simply used this example to help me on the same issue in a different format.

+2
source

RoyalleBlue's answer is correct if only foreach binding is used. But using the Repeat binding will make your binding code much cleaner:

 <ul> <li data-bind="repeat:Reviews.length"> <a href="#" data-bind="text:Reviews[$index]"></a> <span data-bind="text:TeacherNames[$index]"></span> </li> </ul> 

http://jsfiddle.net/mbest/p2kHU/

+2
source

Your property is called TeacherNames, but you call it by the name TeacherName.

Also, it is on the parent object, so try:

 data-bind="text:$parent.TeacherNames[$index()]" 
+1
source

EDIT: The scope (context) is incorrect. You can access TeacherNames with $ parent or $ root.

Modified by:

 <span data-bind="text:TeacherNames[$index()]" >123</span> 

To:

 <span data-bind="text:$parent.TeacherNames[$index()]" >123</span> 

http://jsfiddle.net/calvinslusarski/7xuKX/2/

-1
source

Source: https://habr.com/ru/post/1480473/


All Articles