Prashant Bagare
Prashant Bagare

Reputation: 21

How to use dynamic observable variable names in html files in knockoutjs

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

Answers (2)

Prashant Bagare
Prashant Bagare

Reputation: 21

Hey it worked with vm['product'+product.id()]

Upvotes: 1

Roy J
Roy J

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

Related Questions