Reputation: 21
I am using knockjs and I have created dynamic observableArrays in js file.
Ex. product+productid
which creates a dynamic observableArrays as product123
.
I want to use this in a data bind foreach loop and want to create this variable dynamically again in html file.
Something like : data-bind="foreach: { data: "product"+product.id()()}
So this "product"+product.id()()
binding should call my product123() array.
How can I achieve this?
Upvotes: 1
Views: 702
Reputation: 43881
You can use $data
to refer to the current context, and use array notation to index your dynamically-named element.
vm = {
product: ko.observable('123'),
product123: ko.observableArray([
'one', 'two', 'three'
])
};
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: $data['product'+product()]">
<div data-bind="text: $data"></div>
</div>
Upvotes: 0