I have a ViewModel that looks like:
{
empName: [
{ name: 'NAME1' },
{ name: 'NAME2' }
]
}
I want to display different department names according to my empName
while looping through name
property using a switch statement.
such that output is:
Department 1
Department 2
I tried the following:
<ul data-bind="foreach: empName">
<div data-bind="switch: name">
<div data-bind="case: 'Name1'">
Department 1
</div>
<div data-bind="case: 'Name2'">
Department 2
</div>
<div data-bind="case: $default">
</div>
</div>
But I get the following output:
Department 1
Department 2
Department 1
Department 2
How can I achieve this?
A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .
Why not rethink the problem a little and move this logic into a function? As a rule of thumb, I try to keep my bindings as simple as possible and put the logic into my javascript.
Here is a full example:
var viewModel = {
empName: [
{ name: 'NAME1' },
{ name: 'NAME2' }
]
};
viewModel.departmentName = function(name) {
var departmentName = "Department ";
switch (name) {
case "NAME2":
departmentName += "2";
break;
case "NAME1":
default:
departmentName += "1";
break;
}
return departmentName;
}.bind(viewModel);
ko.applyBindings(viewModel);
and then in your markup:
<ul data-bind="foreach: empName">
<li data-bind="text: viewModel.departmentName(name)"></li>
</ul>
which outputs:
Department 1
Department 2
JSFiddle Demo
departmentName
function:
return name === "NAME2" ? "Department 2" : "Department 1";
My two cents!! Knockout does not have a switch case statement. As suggested by RP Niemeyer
Michael Best's switch/case binding (https://github.com/mbest/knockout-switch-case) is quite flexible and can let you easily handle this and more complicated ones (more states than true/false).
Else you could use condition binding as :
<!-- ko if: name == 'NAME1' -->
<div data-bind="if: name == 'NAME1'">Department 1</div>
<!-- /ko -->
Also,
<div data-bind="if: name == 'NAME1'">Department 1</div>
Demo
There is no switch but you can use if:
<div data-bind="foreach: empName">
<div data-bind="if: name == 'Name1'">
Department 1
</div>
<div data-bind="if: name == 'Name2'">
Department 2
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With