I have a view model that has two arrays. I want to iterate over one array and access the value at the same index on the other array, but it seems that you can't use $parent
with $index
. See here:
function viewModel(factors,models) {
this.name="parent View model";
this.factors = ko.observableArray(factors);
this.models = ko.observableArray(models);
}
function subViewModel(name, array) {
this.anotherArray = ko.observableArray(array);
this.name = name;
}
ko.applyBindings(new viewModel(
["factor1","factor2"],
[ new subViewModel("model1", ["foo","bar"]),
new subViewModel("model2", ["one","two"])
]));
<div data-bind="text:name"></div><hr/>
<div data-bind="foreach:models">
<div data-bind="text: $parent.factors()[$index]"></div>
<div data-bind="text:name"></div>
<hr/>
</div>
If you change $parent.factors()[$index]
to $parent.factors()[0]
it will display the right entry from the factors
array. If you replace it with just $index
, you get the right indexes. But if you combine them, it seems knockout isn't able to parse $index
in an expression that already has $parent
?
Anybody else seen this?
I know I could combine my arrays into a single array of a view model that combines the properties, but I have a reason for not doing that. This is part of a much more complex view model.