不能为ng-model的select设置默认值

can't set default value for select with ng-model

本文关键字:设置 默认值 select ng-model 不能      更新时间:2023-09-26

我试图设置<select>字段数据的默认值,这是与$http

视图:

<select ng-options="dia for dia in ctrl.campos.dataNascimento.dias"  ng-model="ctrl.diaSelected></select>
<select ng-options="mes for mes in ctrl.campos.dataNascimento.meses" ng-model="ctrl.mesSelected"></select>
<select ng-options="ano for ano in ctrl.campos.dataNascimento.anos" ng-model="ctrl.anoSelected"></select>

控制器:

getData.userFacul().then(function(curriculo){
            var dataNascimento = perfilEstudante.curriculo.nascimento;
            dataNascimento = dataNascimento.split('-');
            perfilEstudante.mesSelected = campos.dataNascimento.meses[+dataNascimento[1]-1];
            perfilEstudante.diaSelected = campos.dataNascimento.dias[+dataNascimento[2]-1];

由于getData.userFacul()为$http请求服务。

我用{{}}打印视图上的值,它们显示正确的值。select框显示所有值,但第一个(默认值)为空。更改所选选项也会更改控制器上的变量。我只是不明白为什么我不能设置selectbox的默认值。当我尝试在$http请求之外设置它们时,它可以工作。什么好主意吗?

编辑:我做了一些测试,由于某种原因,当我在$http请求中声明选择框的ng-models时,这些值没有设置为视图的默认值。但是,在$http请求之外,它可以工作。

问题是Angular 不知道你已经更新了值,所以不执行文摘。为了"通知"Angular属性发生了变化,你可以使用$scope.$apply()方法。像这样:

getData.userFacul().then(function(curriculo){
    var dataNascimento = perfilEstudante.curriculo.nascimento;
    dataNascimento = dataNascimento.split('-');
        perfilEstudante.mesSelected = campos.dataNascimento.meses[+dataNascimento[1]-1];
    perfilEstudante.diaSelected = campos.dataNascimento.dias[+dataNascimento[2]-1];
    $scope.$apply();
});