我正在尝试运行 this示例从具有分层数据的选择中选择一个选项,但它不起作用。
$scope.options = [
{ id: 1, info: { label: "Item 1" } },
{ id: 2, info: { label: "Item 2" } },
{ id: 3, info: { label: "Item 3" } }
];
angular.module("selectOptionsTest", [])
.controller("SelectOptionsController", ["$scope", function ($scope) {
$scope.options = [
{ id: 1, info: { label: "Item 1" } },
{ id: 2, info: { label: "Item 2" } },
{ id: 3, info: { label: "Item 3" } }
];
$scope.selectopt = function () {
$scope.opt = { id: 1, info: { label: 'Item 1' } };
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.1/angular.js">
</script>
<div ng-app="selectOptionsTest" ng-controller="SelectOptionsController">
<select ng-model="opt"
ng-options="option.id as option.info.label for option in options"></select>
<input type="button" ng-click="selectopt()" value="select" />
</div>
编辑1:
在这里,我添加了与 plunker 代码大部分相似的代码。
Controller 代码:
(function () {
'use strict';
angular
.module('app.module')
.controller('SomeController', SomeController);
SomeController.$Inject = [
'$scope'
];
function SomeController(
$scope
) {
$scope.GetOptions = function () {
OptionsService.Get().then(function (response) {
$scope.Options = response.value;
}, ErrorHandlerService.ShowError);
};
$scope.GetOptions();
$scope.Edit = function (index) {
$scope.SelectedOption = $scope.Options[index].id;
};
}
})();
HTML 代码:
<select name="Contrato" class="form-control" ng-model="SelectedOption" required autofocus ng-disabled="!IsEditMode"
ng-options="c.id as c.info.name for c in Options track by c.id">
</select>
选项 JSON
[
{
"info":{
"name":"AAA"
},"id":1
},
{
"info":{
"name":"BBB"
},"id":2
}
]
最佳答案
在您的情况下,$scope.opt
模型保存选择。但当你展示它时,你并没有真正使用整个对象。因此,$scope.opt 不包含整个对象,只包含 option.id。因此,为了使其工作,您需要手动为模型分配一个 id。
$scope.selectopt = function () {
$scope.opt = 1;
};
在本例中,您为其分配 1
,这是当前选项中第一个对象的 id。
理想情况下,使用变量而不是硬编码,例如:
$scope.selectopt = function () {
$scope.opt = $scope.options[0].id;
};
关于javascript - 未选择具有分层数据的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38105969/