\$\begingroup\$
\$\endgroup\$
The following code is used to show/hide components in an AngularJS app:
var vm = this;
var hideComponents = function()
{
vm.showRegions = false;
vm.showAccounts = false;
vm.showOrders = false;
vm.showInvoices = false;
vm.showWarehouses = false;
}
vm.showComponent = function(componentName)
{
hideComponents();
switch (componentName) {
case "Regions":
vm.showRegions = true;
break;
case "Accounts":
vm.showAccounts = true;
break;
case "Orders":
vm.showOrders = true;
break;
case "Invoices":
vm.showInvoices = true;
break;
case "Warehouses":
vm.showWarehouses = true;
break;
default:
}
}
Is there a more concise way to achieve this functionality?
I was thinking something along these lines:
var setComponentVisibility = function (componentName = null)
{
var bool = false;
var map = {
'Regions': vm.showRegions = bool,
'Accounts': vm.showAccounts = bool,
'Orders': vm.showOrders = bool,
'Invoices': vm.showInvoices = bool,
'Warehouses': vm.showWarehouses = bool
}
if (componentName != null)
{
// code to set bool to true only for that componentName in map
// is this even possible?
// if so, how?
}
}
However, being new to AngularJS, I'm not sure the above is possible.
Malachi
29k11 gold badges86 silver badges188 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
You can use Bracket Notation to have custom object key by ['text'+variable]
.
vm.showComponent = function(componentName)
{
hideComponents();
vm['show' + componentName]=true;
}
-
\$\begingroup\$ Answers with just code and without some explanation are not good answers. And as the code you have given is sloppy (no spaces between operators and missing a
;
) I am down voting your answer. \$\endgroup\$Blindman67– Blindman672018年08月24日 05:35:46 +00:00Commented Aug 24, 2018 at 5:35 -
1\$\begingroup\$ @Blindman67 edited, but the code itself was self-explanation ,do you think adding that text helps user better understanding,rather than the looking the code? \$\endgroup\$sbk201– sbk2012018年08月24日 05:54:08 +00:00Commented Aug 24, 2018 at 5:54
-
\$\begingroup\$ The OP does not seam to be aware of bracket notation. An explanation of bracket notation (or a link) would improve the answer. \$\endgroup\$Blindman67– Blindman672018年08月24日 06:00:14 +00:00Commented Aug 24, 2018 at 6:00
-
\$\begingroup\$ The addition of bracket notation information was helpful. Much appreciated. \$\endgroup\$knot22– knot222018年08月31日 13:19:47 +00:00Commented Aug 31, 2018 at 13:19
default