如何定义 ng-options 选定值并将其分配给模型?

How to define ng-options selected value and assign this to model?

我有一个这样的数据,我将其编译为 select 选项并在其中 selected 值定义为 defaultValue: 1

content: [
    {
        value: "Bireysel",
        key: "1",
        defaultValue: 0
    },
    {
        value: "Kurumsal",
        key: "2",
        defaultValue: 1
    },
    {
        value: "Bireysel & Kurumsal",
        key: "3",
        defaultValue: 0
    }
]

我可以将其转换为 select opitons 并将用户的 selected 值发送到服务器。

<select ng-model="model.customer" ng-options="item.key as item.value for item in model.properties['CUSTOMER']" name="customer" required>
</select>

但是当我尝试定义 selected 值时,我无法发送到服务器。我试过了 track by 但它 select 包含所有选项字段,我无法将 selected 字段发送到服务器。


<select ng-model="model.customer" ng-options="item.key as item.value for item in model.properties['CUSTOMER'] track by defaultValue" name="customer" required>
</select>

我也试过 ng-repeat 而不是 ng-options。这种方法看起来很脏,它 select 的默认值为 true 但如果用户没有更改任何选项,我无法将真实数据发送到服务器。这是因为 ng-selected 没有为我的模型分配默认值:model.customer

<select ng-model="model.customer" name="customer" required>
    <option ng-repeat="item in model.properties['CUSTOMER']" value="{{item.key}}" ng-selected="item.defaultValue">{{item.value}}</option>
</select>

我如何设法使用 ng-options 定义默认值并将其分配给我的模型以将真实数据发送到服务器?

可以使用 ng-init 设置模型的默认值,如下所示:

<select ng-model="customer" ng-init="customer = content[0].key" ng-options="item.key as item.value for item in content" name="customer" required>

JSFiddle here

var CONTRIBUINTE = -1,
        IMOVEL = -2,
        ECONOMICO = -3,

     $scope.tiposConsulta = [
        { Id: CONTRIBUINTE, Descricao: 'Contribuinte' },
        { Id: IMOVEL, Descricao: 'Imóvel' },
        { Id: ECONOMICO, Descricao: 'Econômico' }];

$scope.tiposConsultaSelected = CONTRIBUINTE;


<select id="tipoConsulta" class="btn form-control"
                        ng-model="tiposConsultaSelected"
                        ng-options="tipo.Id as tipo.Descricao for tipo in tiposConsulta">
                    </select>