Search code examples
javascriptangularjscontrollerng-optionsng-init

Set default value in <select> with angular ng-options maybe using ng-init


I have this in html

<select ng-model="inventory.condition"
        ng-init="inventory.condition = con"
        ng-options="con.name for con in conditions"
    <option >-- choose condition --</option>
</select>
{{inventory.condition}}

On js angular controler:

$scope.conditions = [
        {"name":"New","id":101},
        {"name":"Used","id":102},
        {"name":"Like new","id":103},
        {"name":"Not Working","id":104}
] 
$scope.inventory.condition = {"name":"Used","id":102};

The SELECT populate works fine, and if I select a item on list it set ng-model correctly and Htlm displays correctly the model selected (I want to get the complete model selected, not only the "id" value), but I can't set the default value when build the list.

The idea is receive a model (js object) that contains the default value (what really coming from a html request from a WS that is previously persisted on DB) and select the default item with the value from model, and if user selects a new item, it can changes the same model (what I will update/persist again later).


Solution

  • The thing is that $scope.inventory.condition must be $scope.conditions array element, and two objects are equal only when they are the same object. So you can't just set $scope.inventory.condition = {"name":"Used","id":102};: event though {"name":"Used","id":102} looks like the second value of array, in reality they are not equal, so Angular will not set it as default value.

    You need to set model value like this:

    $scope.conditions = [
        {"name":"New","id":101},
        {"name":"Used","id":102},
        {"name":"Like new","id":103},
        {"name":"Not Working","id":104}
    ];
    $scope.inventory.condition = $scope.conditions[1];