Reputation: 3310
I have added a few observable objects
into an observableArray
: dynaobs
and they look like:
"dynaobs": [
{
"SpecName": "reportingcurrency",
"SpecValue": "EUR"
},
{
"SpecName": "transactionscurrency",
"SpecValue": "GBP"
}
]
I can view the values like below:
<div class="col-sm-6" data-bind="foreach: { data: dynaobs, as: 'ct' }">
<input type="text" data-bind="value: ct.SpecValue" />
</div>
However, I want to bind only the first index of my observableArray to an input control such as below, but it gives me an error:
<div data-bind="value: dynaobs()[0]">
<input type="text" data-bind="value: $data" />
</div>
I have tried:
<div data-bind="value: dynaobs()[0]">
<input type="text" data-bind="value: $parent.SpecValue" />
</div>
<div data-bind="value: dynaobs[0]">
<input type="text" data-bind="value: $parent.SpecValue" />
</div>
and many more, but no luck. Any ideas?
EDIT: This is how I am adding the observables:
for (var i = 0; i < data.specifications.length; i++) {
if (data.specifications[i].controlname != null) {
conv(data.specifications[i].controlname, data.specifications[i].specvalue);
}
}
and calling:
function conv(lbl, val) {
this[lbl] = ko.observable(val);
dynaobs.push(this[lbl]);
}
Upvotes: 0
Views: 126
Reputation: 18525
Is there a reason you bind the parent div value
and then pass $data
when you can just provide the value binding directly to the input?
var ViewModel = function() {
this.arr = ko.observableArray([
{
"SpecName": "reportingcurrency",
"SpecValue": "EUR"
},
{
"SpecName": "transactionscurrency",
"SpecValue": "GBP"
}
])
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div>
<input type="text" data-bind="value: arr()[0].SpecValue" />
</div>
Upvotes: 1