Chapter 5
If the directive generates the empty option, it will be shown only when
the model does not match any items in the list. So the user will not be
able to manually set the select value to null/undefined.
It is possible to hide the empty option by defining your own and setting its style to
display: none.
<option style="display:none" value=""></option>
Try it at http://bit.ly/ZeNpZX.
In this case the select directive will use our empty option but the browser will not
show it. Now, if the model does not match any options the select directive will be
blank and invalid but there will not be a blank option shown in the list.
Understanding select and object equivalence
The select directive matches the model value to the option value using the object
equivalence operator (===). This means that if your option values are objects and
not simply values (like numbers and strings) you must use a reference to the actual
option value for your model value. Otherwise the select directive will think that
the objects are different and will not match it to the option.
In a controller we might set up the options and selected items as an array of objects:
app.controller('MainCtrl', function($scope) {
$scope.sourceList = [
{'id': '10005', 'name': "Anne"},
{'id': '10006', 'name': "Brian"},
{'id': '10007', 'name': "Charlie"}
];
$scope.selectedItemExact = $scope.sourceList[0];
$scope.selectedItemSimilar = {'id': '10005', 'name': "Anne"};
});
Here, selectedItemExact actually references the first item in the sourceList, while
selectedItemSimilar is a different object, even though the fields are identical:
<select
ng-model="selectedItemExact"
ng-options=" item.name for item in sourceList">
</select>
<select
ng-model="selectedItemSimilar"
ng-options="item.name for item in sourceList">
</select>