foreout on knockoutjs

时间:2017-03-26 08:41:52

标签: knockout.js

我正在使用knockly js模板,其中我有三个单选按钮,这些是在foreach循环下。所以我要找的是给这个名字循环。

但我很难做到这一点。 这是我的代码

<div class="form-horizontal" id="ko-bind-element">
            <input type="hidden" id="serverJSON" value="@Newtonsoft.Json.JsonConvert.SerializeObject(Model)" />
            <div data-bind="foreach: procedures">
                <div data-bind="template: { name: Mode(), data: $data }"></div>
            </div>
        </div> 

<script type="text/html" id="procedure">
            <table class="table table-bordered" >
                <tr>

                    <td class="col-md-3"><span data-bind="text: Name"></span></td>

                    <td><input type="radio" data-bind="attr: { name: form08 + '$index' },checked: AlreadyCompleted" /></td>
                    <td><input type="radio" data-bind="attr: { name: form08 + '$index' },checked: NotApplicable" /></td>
                    <td><input type="radio" data-bind="attr: { name: form08 + '$index' },checked: CreateNew" /></td>


                </tr>
                <tr>
                    <td colspan="4" style="padding:0;">

                        <div data-bind="if: CreateNew">
                            <textarea style="margin-top:10px; margin-bottom:10px;" class="col-md-offset-3 col-md-8" data-bind=" value : Text"></textarea>
                            <div class="clearfix"></div>
                        </div>
                    </td>
                </tr>
            </table>

        </script>

现在你可以看到我已经尝试过两种方式。

  1. 简单名称属性并将$index分配给
  2. attr: { name: form08 + '$index' } data-bind,但没有一个工作

1 个答案:

答案 0 :(得分:1)

如果代码attr: { name: form08 + '$index' }的预期结果类似于

  • 名= “form081”
  • 名= “form082”
  • ...

然后你应该将报价移到form08。所以它就像这个attr: { name: 'form08' + $index }

此外,如果所有3个单选按钮都相关,则应将它们指向相同的可观察对象,如下面的示例

function ViewModel() {
  var self = this;
  self.selectedOption = ko.observable("AlreadyCompleted");
}   

$(document).ready(function () {
  var myViewModel = new ViewModel();
  ko.applyBindings(myViewModel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div>
  <input type="radio" value="AlreadyCompleted" data-bind="checked: selectedOption " />Already Completed
  <input type="radio" value="NotApplicable" data-bind="checked: selectedOption " />Not Applicable
  <input type="radio" value="CreateNew" data-bind="checked: selectedOption " />Create New
</div>
<div data-bind="text: selectedOption"></div>