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

2019-08-31 05:55发布

问题:

I'm trying to set a default value for <select> field data that is get with $http

View:

<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>

Controller:

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];

As getData.userFacul() is the $http request service.

I print the values on the view with {{}} and they show the correct values. The select boxes show all values, but the first one, which is default, is blank. Changin the option selected also changes the variables on the controller. I just don't understand why I cant set the default values of selectbox. When I try to set them Outside of the $http request, it works though. Any ideas?

EDIT: I made some tests, and for some reason when I declare the ng-models of the selectboxes inside a $http request, these values aren't set as default on the view. However, outside the $http request it works.

回答1:

The problem is that Angular doesn't know you have updated the value and so doesn't perform a digest. In order to 'notify' Angular that a property has changed you can use the $scope.$apply() method. Like so:

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();
});