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

时间:2015-03-06 11:15:51

标签: javascript angularjs model ng-options

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

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

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

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

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


<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。这个方法看起来很脏,它选择默认值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定义默认值并将其分配给我的模型以将真实数据发送到服务器?

2 个答案:

答案 0 :(得分:2)

可以使用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

答案 1 :(得分:0)

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>