7

I have a number of items that get their data from a Json object and populate it using angular.

<select ng-model="MyCtrl.cargoList">
    <option ng-repeat="cargo in MyCtrl.cargoList">{{ cargo.name }}</option>
</select>

And whenever I load the form, I get something like this in my console:

<select ng-model="MyCtrl.cargoList">
    <option value="? object:25 "?></option>
    <option value="">Gloves</option>
    <option value="">Jacket</option>
    <option value="">Shoes</option>
</select>

I can get the values to appear just fine, but I can't seem to get rid of the very first option. I don't mind the select box showing the very first element in the list, but I don't want it to be a blank line. How do I get rid of it?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Miles Peterson
  • 265
  • 1
  • 4
  • 12

3 Answers3

2

You need to select 1st option by default on ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name" & ng-model name should not be same as that of your cargoList.

Markup

<select ng-model="MyCtrl.selectedCargo" ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name">
    <option ng-repeat="cargo in MyCtrl.cargoList" value="cargo.name">{{ cargo.name }}</option>
</select>

Demo Plunkr

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

Use ng-options instead of ng-repeat

 <select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList"></select>

You can fine tune the labels/values further if you like, check the documentation here - https://docs.angularjs.org/api/ng/directive/ngOptions

You can ng-init, or set the first value to defualt, something like

MyCtrl.selectedListItem = MyCtrl.cargoList[0]

So if you want a function to detect you have changed the value of the select you would use ng-change like so :

<select ng-model="MyCtrl.selectedListItem" ng-options="cargo for cargo in MyCtrl.cargoList" ng-change="selectChanged"></select>

In your controller

$scope.selectChanged = function(){
 //apply your logic
};
ajmajmajma
  • 13,712
  • 24
  • 79
  • 133
0

Use ngOption <option>

The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.

I have used following expression

label for value in array

HTML

<select ng-model="MyCtrl.cargo" ng-options="cargo.name for cargo in MyCtrl.cargoList">
</select>

and In your controller set model value as first element of list

this.cargo = this.cargoList[0]

Also note: You can use MyCtrl.cargoList as model as well as array So you should use another variable to hold the model value.

Satpal
  • 132,252
  • 13
  • 159
  • 168