2017-03-01 64 views
0

我有一个JSON有效载荷通过ajax调用传递给我的挖空视图模型。有效载荷的结构类似于:动态渲染控制和绑定到他们在淘汰赛?

{ 
    "categories":[ 
     { 
     "name":"Category 1", 
     "questions":[ 
      { 
       "id": 1, 
       "questionText":"Question?", 
       "controlType":"text" 
      }, 
      { 
       "id": 2, 
       "questionText":"Question?", 
       "controlType":"radiobutton", 
       "possibleAnswers":[ 
        { 
        "answerId":1, 
        "text":"Yes" 
        }, 
        { 
        "answerId":2, 
        "text":"No" 
        } 
       ] 
      } 
     ] 
     } 
    ] 
} 

在我的模板,我有一个foreach循环遍历所有的类别,然后第二个foreach循环对所有的该类别的问题进行迭代。我需要动态地创建基于所述每一个问题的“controlType”输入,选择,和文字区域,然后结合这些与类似结构的observableArray:

[ 
    { 
     "questionId":1, 
     "answerId":1 
    } 
] 

我制成一个函数,可以动态在foreach中呈现html,但我不知道如何完成剩下的工作。

这里有一个演示模板:

<div data-bind="foreach:categories"> 
    <h2 data-bind="text:name"></h2> 
    <div data-bind="foreach:questions"> 
     <span data-bind="text:questionText"></span> 
     <div data-bind="html:$parents[0].createControl($data)"></div> 
    </div> 
</div> 

我将如何绑定,结果从这些输入存储?

回答

1

我认为在这里使用templates以及if binding会很明智。

<div data-bind="foreach:categories"> 
    <h2 data-bind="text:name"></h2> 
    <div data-bind="foreach:questions"> 
     <span data-bind="text:questionText"></span> 
     <!-- ko if: controlType() == "radiobutton" --> 
      <div data-bind="template: { name: 'radio-template', data: $data }"></div> 
     <!-- /ko --> 
     <!-- ko if: controlType() == "other-type" --> 
      <div data-bind="template: { name: 'other-type-template', data: $data }"></div> 
     <!-- /ko --> 
     <!-- ... --> 
    </div> 
</div> 

你可以定义模板是这样的:

<script type="text/html" id="radio-template"> 
    <h3 data-bind="text: questionText"></h3> 
    <div data-bind="foreach:possibleAnswers"> 
     <!-- you html here --> 
    </div> 
</script> 

至于存储的答案,为什么不加selectedAnswer的问题吗?

{ 
    "categories":[ 
     { 
     "name":"Category 1", 
     "questions":[ 
      { 
       "id": 1, 
       "questionText":"Question?", 
       "controlType":"text" 
      }, 
      { 
       "id": 2, 
       "questionText":"Question?", 
       "controlType":"radiobutton", 
       "possibleAnswers":[ 
        { 
        "answerId":1, 
        "text":"Yes" 
        }, 
        { 
        "answerId":2, 
        "text":"No" 
        } 
       ], 
       "selectedAnswer": -1 
      } 
     ] 
     } 
    ] 
} 

另一个解决方案是有答案的阵列和问题ID:

{ 
    "categories":[ 
     { 
     "answers": [ "questionId": 1, "answer": { "id": -1, "value": "" } ] 
     "name":"Category 1", 
     "questions":[ 
      { 
       "id": 1, 
       "questionText":"Question?", 
       "controlType":"text" 
      }, 
      { 
       "id": 2, 
       "questionText":"Question?", 
       "controlType":"radiobutton", 
       "possibleAnswers":[ 
        { 
        "answerId":1, 
        "text":"Yes" 
        }, 
        { 
        "answerId":2, 
        "text":"No" 
        } 
       ] 
      } 
     ] 
     } 
    ] 
}