I am trying to learn knockout and have come up against a problem.
I am trying to use the ko if clause but can’t seem to work it out myself
My script so far looks like
<script>
var SimpleListModel = function (items) {
this.questionType = ko.observable("");
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function () {
if (this.itemToAdd() != "") {
var qt = $("#question-type").data("kendoDropDownList");
this.questionType(qt.value());
console.log(qt.value());
this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
}
}.bind(this); // Ensure that "this" is always this view model
};
$(document).ready(function () {
ko.applyBindings(new SimpleListModel([]));
});
</script>
My html looks like
<button type="submit" class="btn pull-right" data-bind="enable: itemToAdd().length > 0"><i class="icon-plus"></i>Add Question</button>
<div id="questions" data-bind="foreach: items">
<div class="question-item">
<label data-bind="text: $data" class="q-label"></label>
<textarea placeholder="Answer" class="q-answer"></textarea>
<!-- ko if: questionType()==="ABC" -->
Display ABC
<!-- /ko -->
<!-- ko if: questionType()==="DEF" -->
Display DEF
<!-- /ko -->
</div>
<div class="clear"></div>
</div>
What do I need to do, to get the ko if: questionType to work correctly?
I have updated the setting of the questionType as suggested however I am getting an error Uncaught Error: Unable to parse bindings.
Message: ReferenceError: questionType is not defined;
Bindings value: if:questionType()==="Comment"
Since
questionTypeis an observable you need to call it as a function with no arguments to retrieve its value.So, your
ifstatements would need to look like: