Search code examples
knockout.jsknockout-2.0knockout-mvc

not able to get the last index inside foreach knockout.js


I am not able to get the last of observableArray index inside foreach in gsp page as below

<!-- ko foreach: $data.audienceInformation.IndivisualUsers -->
  <span data-bind="html:$index()"></span>        //Here index is coming correctly
  <span data-bind="html:$last"></span>           //i want last index here
  <span data-bind="html:$data+','"></span>
<!-- /ko -->

This is my JSON data

{
    "AccountMessagesHistory": {
        "audienceInformation": {
            "Accounts": ["DHL"],
            "IndivisualUsers": ["[email protected]"]
        },
        "documentInformation": ["Name: ",
               "Title: <p>aa</p>",
               "Description: <p>aa</p>",
               "Document Type: text",
               "This document belongs (creator/last modifier) to: b2b:[email protected]",
               "This document is published for the language: en_US",
               "This document was created on: Mon Mar 03 03:15:09 MST 2014",
               "This document was last modified on: Mon Mar 03 03:15:09 MST 2014",
               "This document is a text document",
               "This document will be available from: Mon Mar 03 00:00:00 MST 2014",
               "This document will be available until: Tue Mar 03 00:00:00 MST 2015",
               "This document is available under message feature card"],
        "documentHistory": ["User ID: b2b:[email protected]      Name: HP Admin,ITG      Modified On: Mon Mar 03 03:15:09 MST 2014"]
    }
}

Solution

  • Instead of $last, use the .length of the array:

    <span data-bind="text: ko.utils.unwrapObservable($parent.audienceInformation.IndivisualUsers).length - 1"></span>