Search code examples
razorknockout.jsknockout-mvc

Nested element not getting generated in knockout :foreach


This is my HTML code:

<div class="crs-wt-dropbox crs-wt-dropbox-row" data-bind="foreach :rowCols">
   <span class="crs-wt-drop-item" data-bind="text: text"> <a class="close-ico" href="#" > </a></span>
</div>

where foreach :rowCols rowCols will updated dynamically: so, after adding few values to rowCols, it has generated following code

<div class="crs-wt-dropbox crs-wt-dropbox-row" data-bind="foreach :rowCols">
<span class="crs-wt-drop-item" data-bind="text: text">Account</span>
<span class="crs-wt-drop-item" data-bind="text: text">Account number</span>
</div>

but I'm wondering why it doesn't generated any anchor tag?


Solution

  • Your data-bind="text: text" binding replaces inner content of the span. So you get "Account" text instead of the anchor tag.

    Update 1

    If I've understood your requirements right, to overcome this behavior you should move the "text" binding into the anchor element:

     <span class="crs-wt-drop-item"><a class="close-ico" href="#" data-bind="text: text"></a></span>
    

    Update 2

    It seems to me like this code snippet solves the task:

    var model = { rowCols: [ { text: 'Item 1'}, { text: 'Item 2'} ] }
    
    ko.applyBindings(model);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    
    <div class="crs-wt-dropbox crs-wt-dropbox-row" data-bind="foreach: rowCols">
       <span class="crs-wt-drop-item"><a class="close-ico" href="#" data-bind="text: text"></a></span>
    </div>