2
\$\begingroup\$

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
asked Aug 23, 2018 at 13:07
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can use Bracket Notation to have custom object key by ['text'+variable].

vm.showComponent = function(componentName)
{
 hideComponents();
 vm['show' + componentName]=true;
}
answered Aug 23, 2018 at 14:13
\$\endgroup\$
4
  • \$\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\$ Commented 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\$ Commented 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\$ Commented Aug 24, 2018 at 6:00
  • \$\begingroup\$ The addition of bracket notation information was helpful. Much appreciated. \$\endgroup\$ Commented Aug 31, 2018 at 13:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.