2

Let's say I have a $scope variable that stores a vegetable like so:

$scope.selectedVegetable = 'carrot';

And I also have an object that contains properties of vegetables like so:

$scope.vegetableProperties = {
    carrot: {
        color: 'orange',
        tastiness: 3
    },
    onion: {
        color: white,
        tastiness: 1
    }
};

And now let's say that I want to use the value of $scope.selectedVegetable to help me specify the object/property in $scope.vegetableProperties that I am looking for.

What I'd like to do is something like...

$scope.selectedColor = $scope.vegetableProperties.$scope.selectedVegetable.color;

...rather than explicitly specifying the vegetable, as in:

$scope.selectedColor = $scope.vegetableProperties.carrot.color;

and expect a value of orange, but this does not work.

Basically, is there a way to use the value of one $scope variable to specify an object property on another $scope variable?

Graham Bewley
  • 195
  • 3
  • 13
  • 1
    Bracket notation: `$scope.vegetableProperties[$scope.selectedVegetable].color`. I suggest you go through some introductory lessons on JS before tackling AngularJS. – JLRishe Jun 18 '19 at 20:01

1 Answers1

2

It's not specific to AngularJS, but you should be able to access object properties by variable like so: $scope.selectedColor = $scope.vegetableProperties[$scope.selectedVegetable].color;

Javascript use variable as object name

RSchneyer
  • 300
  • 1
  • 8