Javascript 使用$scope变量的值指定属性
假设我有一个$scope变量,它存储一种蔬菜,如下所示:Javascript 使用$scope变量的值指定属性,javascript,angularjs,Javascript,Angularjs,假设我有一个$scope变量,它存储一种蔬菜,如下所示: $scope.selectedVegetable = 'carrot'; 我还有一个包含蔬菜属性的对象,比如: $scope.vegetableProperties = { carrot: { color: 'orange', tastiness: 3 }, onion: { color: white, tastiness: 1 } };
$scope.selectedVegetable = 'carrot';
我还有一个包含蔬菜属性的对象,比如:
$scope.vegetableProperties = {
carrot: {
color: 'orange',
tastiness: 3
},
onion: {
color: white,
tastiness: 1
}
};
现在让我们假设我想使用$scope.selectedveget
的值来帮助我指定我要查找的$scope.vegetableProperties
中的对象/属性
我想做的是
$scope.selectedColor = $scope.vegetableProperties.$scope.selectedVegetable.color;
…而不是明确指定蔬菜,如:
$scope.selectedColor = $scope.vegetableProperties.carrot.color;
并期望值为橙色
,但这不起作用
基本上,有没有一种方法可以使用一个$scope变量的值来指定另一个$scope变量的对象属性?这不是特定于AngularJS的,但您应该能够通过变量访问对象属性,如下所示:
$scope.selectedColor=$scope.vegetableProperties[$scope.selectedVegetable].color代码>
括号表示法:$scope.vegetableProperties[$scope.selectedvegetar].color
。我建议你在学习AngularJS之前先学习一些关于JS的入门课程。太好了,非常感谢!