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.

\$\endgroup\$
2
\$\begingroup\$

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

vm.showComponent = function(componentName)
{
   hideComponents();
   vm['show' + componentName]=true;
}
| improve this answer | |
\$\endgroup\$
  • \$\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 Aug 24 '18 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 Aug 24 '18 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 Aug 24 '18 at 6:00
  • \$\begingroup\$ The addition of bracket notation information was helpful. Much appreciated. \$\endgroup\$ – knot22 Aug 31 '18 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.