AngularJS 中的动态下拉选择不起作用 [英] Dynamic dropdown select in AngularJS not working
问题描述
我正在练习 Angular,并希望为用户提供从 3 个下拉选择菜单中进行选择的选项.第三个菜单应该是动态的,具体取决于前两个菜单的选择.
I am practicing with Angular and want to give users the option to choose from 3 dropdown select menus. The third menu should be dynamic depending on the selection from the previous two menus.
我的html:
// First dropdown menu, static
<select ng-model="selectedLetter" ng-change="setColorSelection()"
ng-options="letter as letter for letter in letters">
</select>
<br>
// second dropdown menu, static
<select ng-model="selectedNumber" ng-change="setColorSelection()"
ng-options="number as number for number in numbers">
</select>
<br>
// third dropdown menu, should be dynamic
<select ng-model="selectedColor"
ng-options="color as color for color in colorSelection">
</select>
在我的控制器中,我有这样的列表
In my controller, I have the lists like this
$scope.letters = ['A', 'B'];
$scope.numbers = ['1', '2'];
var colors = {
'A1': [{"red": "100"}, {"pink": "101"}],
'A2': [{"blue": "202"}, {"black": "203"}],
'B1': [{"yellow": "304"}, {"orange": "305"}],
'B2': [{"white": "406"}, {"black": "407"}]
};
$scope.colorSelection = [];
$scope.setColorSelection = function() {
if ($scope.selectedLetter && $scope.selectedNumber) {
$scope.colorSelection = colors[$scope.selectedLetter + $scope.selectedNumber];
console.log($scope.colorSelection);
}
}
因此,如果用户从第一个菜单中选择A",从第二个菜单中选择2",他应该会在第三个菜单中看到A2"的选项.
So if the user selects 'A' from the first menu and '2' from the second menu, he should see the options for 'A2' in the third menu.
问题:当前,第三个菜单未填充.
当我执行 console.log($scope.colorSelection) 时,我在控制台中得到 [Object, Object] 而不是 [{"blue": "202"}, {"black": "203"}].
When I do console.log($scope.colorSelection), I get [Object, Object] in the console instead of [{"blue": "202"}, {"black": "203"}].
另外,我只想在菜单中显示颜色,而不是与它们相关的数字.我能够使用 (key, value) 在 ng-repeat 中执行此操作,但不确定如何在 ng-options 中执行此操作.
Also, I only want to display the colors in the menu, not the numbers associated with them. I was able to do this in ng-repeat using (key, value), not sure how I would do this in ng-options.
推荐答案
像这样改变你的颜色对象
Change your color object like
var colors = {
'A1': [{"color": "Red", "code": "100"}, {"color":"pink", "code": "101"}]
};
和 ng-option
and ng-option
<select ng-model="selectedColor"
ng-options="color.code as color.color for color in colorSelection">
</select>
这篇关于AngularJS 中的动态下拉选择不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!