How to access the index of an item in knockout.js template

前端 未结 3 1289
悲哀的现实
悲哀的现实 2021-02-05 11:17

Within my template in tbody below, how can I access the index of the item being rendered?

3条回答
  •  感动是毒
    2021-02-05 11:36

    Update: $index is now available in KO 2.1.

    Currently, there is not a way to directly access the index in a foreach. There is a pull request that looks at adding a $index variable here: https://github.com/SteveSanderson/knockout/pull/182

    An option that I have used in the past is to use a manual subscription against an observableArray that keeps an index observable in sync.

    It works like:

    //attach index to items whenever array changes
    viewModel.tasks.subscribe(function() {
        var tasks = this.tasks();
        for (var i = 0, j = tasks.length; i < j; i++) {
           var task = tasks[i];
            if (!task.index) {
               task.index = ko.observable(i);  
            } else {
               task.index(i);   
            }
        }
    }, viewModel);
    

    Here is a sample: http://jsfiddle.net/rniemeyer/CXBFN/

提交回复
热议问题