angularjs ng-option 空白选项改为预选

angularjs ng-option blank option instead preselected

我在 select 元素中将预先 selected 值显示为 selected 选项时遇到问题。这是代码

<select ng-model="data.company" ng-options="company as company.name for company in companies"></select>


$scope.companies =[{
    id:1,
    name:"Company 1"
},
{
    id:2,
    name:"Company 2"
}];

$scope.data = {
    company:{
        id:2,
        name:"Company 2"
    }
}

问题是,当我进入该部分时,select 给我一个空白选项作为默认显示 "Company 2"。我做错了什么?

试试这个

 <select ng-model="data.company" ng-options="company.name for company in companies"></select>

  $scope.data = {
      company: $scope.companies[1];
  };

您希望下拉列表中显示的值为公司名称,存储的对象为公司。

在这种情况下,您需要使用 track by,因为您是直接将对象值分配给 ng-model。在这种情况下,发生的情况是,当您将对象直接绑定到 data.company(ng-model) track by expression 检查 company.id in that ng-model with the each companies element id。如果有人匹配它,它会在 select 之前输入。

标记

<select ng-model="data.company" 
   ng-options="company as company.name for company in companies track by company.id">
</select>

Demo Plunkr

您可以尝试使用 ng-init

<select ng-init="data.company= companies[0]" 
        ng-model="data.company" 
        ng-options="company as company.name for company in companies"></select>