javascriptangularjsangularjs-ng-options

angularjs prevent ng-option autoselecting last value


I've got a problem here with angularjs, the title is auto explanatory, but my problem is that...

I have two select elements, when I select an option in the first one, ng-change make an Ajax call and the response is used to populate the second select. But when the ajax request completes, $scope.$apply() update everything and the second select element is populated, but the last item is always selected by default. Why? How to prevent it?

The crazy thing is that I have a lot of other select elements, populated via Ajax, and that problem only happens with one specific select.

My HTML

<select class="form-control" ng-model="id_professional"
        ng-options="professional.ID as professional.NAME for professional in listProfessionals">
   <option value="">Select...</option>
</select>

$scope.listProfessionals

[
{ID: "700003655490405", NAME: "Jhon"},
{ID: "700003655490406", NAME: "Lucas"},
{ID: "700003655490407", NAME: "James"},
{ID: "700003655490408", NAME: "Michael"}
]

"Michael" is always selected when the list is populated.

I already tried the following solution, didn't work. Why dropdown selecting last value


Solution

  • So, I've find out what was causing the bug, and it's shameful to say that was just a typo, my fault. Two nights awake are really blowing up my mind.

    The problem was that the Ajax response have a property called IDN and not ID like professional.ID (undefined), typing professional.IDN in ng-options solved my problem.

    Sorry guys. And thanks anyway!

    <select class="form-control" ng-model="id_professional"
            ng-options="professional.IDN as professional.NAME for professional in listProfessionals">
       <option value="">Select...</option>
    </select>