假设我有一个 $scope 变量来存储蔬菜,如下所示:
$scope.selectedVegetable = 'carrot';
我还有一个包含蔬菜属性的对象,如下所示:
$scope.vegetableProperties = {
carrot: {
color: 'orange',
tastiness: 3
},
onion: {
color: white,
tastiness: 1
}
};
现在假设我想使用 $scope.selectedVegetable
的值帮助我指定 $scope.vegetableProperties
中的对象/属性我正在寻找。
我想做的是......
$scope.selectedColor = $scope.vegetableProperties.$scope.selectedVegetable.color;
...而不是明确指定蔬菜,如:
$scope.selectedColor = $scope.vegetableProperties.carrot.color;
期望值为 orange
,但这不起作用。
基本上,有没有一种方法可以使用一个 $scope 变量的值来指定另一个 $scope 变量上的对象属性?
最佳答案
它不是 AngularJS 特有的,但您应该能够通过变量访问对象属性,如下所示:$scope.selectedColor = $scope.vegetableProperties[$scope.selectedVegetable].color;
关于javascript - 使用 $scope 变量的值来指定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56656237/