MattDionis
MattDionis

Reputation: 3616

Concatenate string to form scope property

I'm finding myself repeating a lot of code in my Angular controller because I need to update different properties on my scope based on which element fired the click handler. Below is an example:

vm.toggleEdit = function(activity) {
  if (activity === 'gain') {
    vm.editGain = !vm.editGain;
    vm.newGainLimit = '';
  } else if (activity === 'loss') {
    vm.editLoss = !vm.editLoss;
    vm.newWithdrawalLimit = '';
  } else {
    vm.editNeutral = !vm.editNeutral;
    vm.newNeutralLimit = '';
  }
};

What I'd like to do is utilize the activity parameter more efficiently. For example:

vm.edit + activity = !vm.edit + activity;

Is something like this possible?

Upvotes: 0

Views: 28

Answers (1)

Pointy
Pointy

Reputation: 413826

You can write:

vm["edit" + activity] = whatever;

Note that your activity values start with lower-case letters, so you'll have to deal with that.

Seems like maybe your data structure should look like:

var vm = {
  gain: {
    edit: true,
    newLimit: ''
  },
  loss: {
    edit: false,
    newLimit: ''
  },
  // etc
};

That way your activity value would select a sub-object, and all those would be similar.

Upvotes: 2

Related Questions