无法使用ng-model设置选择的默认值

时间:2015-07-15 19:32:57

标签: javascript angularjs http select

我正在尝试为<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框显示所有值,但第一个值是默认值,为空。 Changin选择的选项也会更改控制器上的变量。我只是不明白为什么我不能设置selectbox的默认值。当我尝试将它们设置在$ http请求之外时,它可以工作。 有什么想法吗?

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

1 个答案:

答案 0 :(得分:0)

问题是Angular 不知道您已更新了值,因此不会执行摘要。为了通知&#39;属性已更改的角度您可以使用$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();
});