Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Delimiter inside foreach of Knockout

Tags:

knockout.js

I need to add comma Delimiter for below observable array

this.Filter = ko.observableArray([{ "Key": "1", "Value": "a" }, { "Key": "2", "Value": "b" }, { "Key": "3", "Value": "c" }]);

I need to show above array like a,b,c

<td data-bind="foreach: Filter">
   <span data-bind="text: value"></span>
</td>

But the value is showing like a b c

like image 953
muthuvel Avatar asked Oct 30 '12 09:10

muthuvel


3 Answers

Quick and dirty

<td data-bind="foreach: Filter">
   <!-- ko if: $index() > 0 -->,<!-- /ko -->
   <span data-bind="text: value"></span>
</td>
like image 66
Anders Avatar answered Oct 05 '22 15:10

Anders


You can do this:

<td data-bind="foreach: Filter">
    <!--ko if: $index() != 0-->,<!--/ko-->
   <span data-bind="text: Value"></span>
</td>

But it is better to have computed that will concatenate arrays values:

self.Filter2 = ko.computed(function (){
    var result = "";
    ko.utils.arrayForEach(self.Filter(), function(item){
        if (!result){
            result = item.Value;
        }
        else{
            result = result + ', ' + item.Value;
        }
    });
    return result;
}); 

Here is fiddle with both variants: http://jsfiddle.net/XrB7z/

like image 25
Artem Vyshniakov Avatar answered Oct 05 '22 16:10

Artem Vyshniakov


The modern CSS way

Same markup + class:

<td data-bind="foreach: Filter" class="comma-separated">
   <span data-bind="text: value"></span>
</td>

CSS:

.comma-separated {
  display: flex;
}

.comma-separated > span + span:before {
  content: ", ";
}
like image 44
Francis Nepomuceno Avatar answered Oct 05 '22 15:10

Francis Nepomuceno