javascriptangularjsng-optionsangularjs-ng-options

Angularjs empty select selector


I currently have a angularjs select with ng-options with the following code:

 <select ng-model="vm.selectedship" ng-change="vm.updateShip()"  data-ng-options="ship as ('ship'  + ' is ready (' + ship.currentlocation + ')') for ship in vm.readyships">

produces this production code:

    <select class="ng-valid ng-dirty ng-touched" data-ng-options="ship as ('ship' + ' is ready (' + ship.currentlocation + ')') for ship in vm.readyships">
<option label="" selected="selected" value="?">
        </option>
    <option label="ship is ready (New york)" value="0">
        ship is ready (New york)
    </option>
    <option label="ship is ready (City2)" value="1">
        ship is ready (City2)
    </option>
    <option label="ship is ready (City3)" value="2">
        ship is ready (City3)
    </option>
    <option label="ship is ready (City24)" value="3">
        ship is ready (City24)
    </option>
    <option label="ship is ready (City24)" value="4">
        ship is ready (City24)
    </option>
</select>

but, when im selecting any of the options, the selected "window" is still blank like this

enter image description here

Q: How can do so the text is within the selector?, and how can i remove the blank option?

EDIT:

currently im using vm.selectedship to get the whole property of the selected ship. If anything here is needed to change, im in need to select the ship to a vm.property somehow else.


Solution

  • The reason you are seeing blank when you are selecting an option is because you are using a string for alias and not a property. So ng-model is not able to find the property to display. Solution for your issue is instead of creating the string on the fly to display, create a property called DisplayText for each object in the controller.

    html

     <select ng-model="vm.selectedship" ng-change="vm.updateShip()"  
    data-ng-options="ship as ship.DisplayText 
    for ship in vm.readyships">
    

    js

     _.each(vm.readyships, function (ship) { 
    _.extend(ship, { DisplayText: "ship is ready (" + ship.currentlocation + ")" });
    });