所以我正在尝试根据某些对象内部的值设置一个select索引。当我遍历对象时,在控制台中我可以看到colorID正在更新和更正,只是选择索引永远不会从上次选择的选项中更改。我错过了什么?提前谢谢。
HTML:
<select
ng-model="colorModel"
ng-change="updateColor(colorModel.id)"
ng-options="i.label for i in colorOptions">
</select>
控制器:
$scope.colorOptions = [
{value: 'red', label: 'Red', id: 0},
{value: 'green', label: 'Green', id: 1},
{value: 'blue', label: 'Blue', id: 2},
{value: 'yellow', label: 'Yellow', id: 3}
];
//setting it here works just fine
$scope.colorModel = $scope.colorOptions[2];
$scope.nextOption = function(){
$scope.groupIndex++;
$scope.currentOption = userOptions[$scope.groupIndex];
$scope.colorModel = $scope.colorOptions[$scope.currentOption.colorID];
//I event tried this with no luck
$scope['colorModel'] = $scope.currentOption.colorID;
}
答案 0 :(得分:2)
您希望$scope.colorModel
中的内容是数组$scope.colorOptions
的颜色对象,但您希望在select
中显示的内容是label
,对吗?然后,ng-options
的正确语法将是:
<select
ng-model="colorModel"
ng-change="updateColor(colorModel.id)"
ng-options="i as i.label for i in colorOptions">
</select>
在控制器中执行以下操作:
app.controller("yourController", function($scope, $filter){
$scope.colorOptions = [
{value: 'red', label: 'Red', id: 0},
{value: 'green', label: 'Green', id: 1},
{value: 'blue', label: 'Blue', id: 2},
{value: 'yellow', label: 'Yellow', id: 3}
];
//setting it here works just fine
$scope.colorModel = $scope.colorOptions[2];
$scope.nextOption = function(){
$scope.groupIndex++;
$scope.currentOption = userOptions[$scope.groupIndex];
$scope.colorModel = $filter('filter')($scope.colorOptions, {id:$scope.currentOption.colorID})[0];
}
});
请注意,您需要在$filter
中注入controller
服务,如下所示:app.controller("yourController", function($scope, $filter){...