Use value of $scope variable to specify a property

Viewed 55

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?

1 Answers

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

Related