sukesh
sukesh

Reputation: 2523

Angularjs 1.2 adds empty option in select

I have a dropdown that gets its items from database. The default value to be selected in this dropdown is retrieved from a cookie. The problem is,
1. there is an empty option tag as the first option and also,
2. the default value is not selected.
There is no issue at all when I use v1.3.16. This happens when using v1.2.0. (I have to use only v1.2.0)
How to fix this.

ASPX:

<select id="ddlItems" data-ng-model="ItemId">
 <option value="-1">-- All Circles --</option>
 <option data-ng-repeat="item in Items" value="{{item.AreaCode}}" 
  data-ng-selected="item.AreaCode==ItemId">{{item.AreaName}}</option>
</select>

Ctrl.js:

var promise = MyFactory.GetItems();
promise.then(function (success) {
 if (success.data != null && success.data != '') {
  var data = success.data;
  $scope.Items = data.lstItems; //bind items to dropdown      
  $scope.ItemId = itemIdFromCookie; //select default value
  alert(itemIdFromCookie); //it pops -1                       
 }
 else {
  console.log(success.data);
 }
}

Rendered HTML:

<select id="ddlItems" data-ng-model="ItemId">
 <option value="? string:"-1" ?"></option>
 <option value="-1">-- All Circles --</option>
 //...other options
</select>

Upvotes: 1

Views: 58

Answers (2)

Shujaath Khan
Shujaath Khan

Reputation: 1384

This happens becausedata-ng-model="ItemId" is empty when your model is App is Loaded.

To Have some initial value. you can put default value in ng-init

For Ex : data-ng-init='data-ng-model="--SELECT--";'

Or per your Array list Item which you are getting from database set one of the values.

Remember init will get triggered b/f you complete the Ajax Call.

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try to use ngOptions instead

Like this

<select id="ddlItems" 
     data-ng-model="ItemId" 
     ng-options="item.AreaCode as item.AreaName for item in Items">
 <option value="-1">-- All Circles --</option>
</select>

Upvotes: 1

Related Questions