动态选择并选择默认值

Dynamic select with default selected

本文关键字:选择 默认值 动态      更新时间:2023-09-26

如何生成一个带有选项和默认选项标记为"selected"的select元素?

例如,我的选项数组:

    $scope.options = [
        {
            "value": 1,
            "label": "One",
            "selected": true
        },
        {
            "value": 2,
            "label": "Two"
        },
        {
            "value": 3,
            "label": "Three"
        }
    ];

和棱角分明的html:

<select name="">
    <option ng-repeat=" option in options " value="{{ option.value }}" ng-selected=" option.selected === true "> {{ option.label }}</option>
</select>

所以,我需要生成这样的东西:

<select name="">
    <option value="1" selected>One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

我想要使用ng-options

感谢

对于这种复杂的对象,使用ng选项是更好的选择。所以你可以用这个代码来做。

<select ng-options="option.value as option.label for option in options" ng-model="yourModel">
</select>

我只添加了ng模型它是ng选项工作所必需的,只需将您的模型设置为您想要的值,它就会自动设置。。。

<select ng-model="selectedOpt" ng-options="option.value for option in options" ng-change="setOption(selectedOpt)">

在您的控制器中,您应该将模型设置为所选的

$scope.selectedOpt = _.find($scope.options, function(o){return o.selected;})
function setOption(opt){
    opt.selected =true;
}

要有默认选项,必须首先填充列表,否则会出现错误或空白选项。您可以在控制器中执行此操作。这是一把小提琴https://jsfiddle.net/rosstroha/3dcthfwh/3/

示例控制器:

var myApp = angular.module('myApp',[]);
angular.module('myApp').controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
    $scope.optionList = [
    {value: "val1"},
    {value: "val2"}
    ]
    $scope.selectedOption = $scope.optionList[0];
}

HTML:

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <select ng-model="selectedOption" ng-options="option.value for option in optionList">
  </div>
</div>

可选地,你可以添加另一个选项,它将永远存在,就像这个

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    <select ng-model="selectedOption" ng-options="option.value for option in optionList">
    <option disabled value="">Select</option>
  </div>
</div>