2017-03-01 35 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" 
        } 
       ] 
      } 
     ] 
     } 
    ] 
}