Reputation: 2914
Basically, I want to 'label' each row my template produces with a 'line number'
eg.
1 [other html]
2 [other html]
3 [other html]
previously, when adding an object to the array (array used by template), I'd count the array items and then add that count to the new object I'm adding to the array...
BUT, now I need to delete, and it's producing something like this on delete :
1 [other html]
3 [other html]
where '2' has been removed, but really I want it to just label the line numbers and not be an id inside the data in the row. So '3' should disappear and '2' should be the last item, even though '2' was the one.
Upvotes: 10
Views: 8641
Reputation: 2842
As of knockout 2.1 (maybe before) you can do
<span data-bind="text: $index"></span>
instead of
<span data-bind="text: ko.utils.arrayIndexOf($parent, $data)"></span>
Updated fiddle - http://jsfiddle.net/u9GWr/140/
Upvotes: 13
Reputation: 3700
Starting from knockout version 2.1 use $index variable instead of arrayIndexOf method (see this answer for example).
I would use with and $parent for this, example http://jsfiddle.net/u9GWr/139/
Html:
<ul data-bind="with: vm.items">
<!-- ko foreach: $data -->
<li><span data-bind="text: ko.utils.arrayIndexOf($parent, $data)"></span>
<span data-bind="text: name"></span>
</li>
<!-- /ko -->
</ul>
JavaScript
vm = {
items: ko.observableArray( [
{name: ko.observable("a")},
{name: ko.observable("b")},
{name: ko.observable("c")},
])
}
ko.applyBindings(vm);
vm.items.splice(2,0, { name: ko.observable('test')});
Output
0 a
1 b
2 test
3 c
Upvotes: 9