Get rid of empty entry in select tag

I have several elements that get their data from a Json object and populate it with 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 ​​so that they look just fine, but I cannot get rid of the very first option. I do not mind the selection box showing the very first item in the list, but I do not want it to be an empty string. How can I get rid of it?

+7
javascript arrays angularjs select
source share
3 answers

You need to select the 1st default option in ng-init="MyCtrl.selectedCargo=MyCtrl.cargoList[0].name" and the ng-model name should not be the same as the name 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

+2
source share

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 labels / values ​​if you want, see 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 the function to detect that you have changed the selection value, you will use ng-change as follows:

 <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 }; 
0
source share

Use ngOption <option>

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

I used the 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 the model value as the first list item

 this.cargo = this.cargoList[0] 

Also note: you can use MyCtrl.cargoList as a model as well as an array. Therefore, you must use another variable to store the model value.

0
source share

All Articles