Javascript 设置选择索引
所以我尝试根据一些对象内部的值设置一个选择索引。当我在对象中循环时,在控制台中我可以看到colorID正在更新和正确,只是选择索引从未改变上次选择的选项。我错过了什么?提前谢谢 HTML:Javascript 设置选择索引,javascript,angularjs,ng-options,Javascript,Angularjs,Ng Options,所以我尝试根据一些对象内部的值设置一个选择索引。当我在对象中循环时,在控制台中我可以看到colorID正在更新和正确,只是选择索引从未改变上次选择的选项。我错过了什么?提前谢谢 HTML: 似乎您希望在$scope.colorModel中显示的是数组$scope.colorOptions的颜色对象,但是您希望在选择中显示的是标签,对吗?然后,ng options的正确语法为: <select ng-model="colorModel"
似乎您希望在
$scope.colorModel
中显示的是数组$scope.colorOptions
的颜色对象,但是您希望在选择中显示的是标签,对吗?然后,ng options
的正确语法为:
<select
ng-model="colorModel"
ng-change="updateColor(colorModel.id)"
ng-options="i as i.label for i in colorOptions">
</select>
请注意,您需要在控制器中插入$filter
服务,如下所示:app.controller(“yourController”,function($scope,$filter){…
感谢您的快速回复。我将其更改为与ng选项示例相匹配,但在选择更改上仍然没有运气。在记录日志时,我可以看到colorModel正在更新,只是选择不更新。奇怪的是,它只显示了您回复中最初的代码块。要回答问题“是”,我想显示与cu关联的标签rrentObject.ID.Object side它正在更新没有问题,只是选择不太好。@Rudy my bad,我错过了问题的另一半,我刚刚更新了我的答案,请看一看,让我知道它是否有效。谢谢!再次感谢Josep的建议。我用你的示例尝试了它,但仍然没有成功。有一件事可以做到更改是当我设置colorModel=$filter…..时,colorModel返回为未定义。@Rudy$scope.currentOption.colorID的值是多少?非常感谢您的示例。$scope.currentOption.colorID与下拉列表设置的值相匹配。查看您的工作示例,我必须缺少一些内容,因为它正在生成我期待的结果。我会逐行比较,看看我遗漏了什么。非常感谢你的帮助。非常感谢!
$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;
}
<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];
}
});