AngularJS 1.4: Select List Value not Initializing Correctly when List is Inserted with $compile AngularJS 1.4: Select List Value not Initializing Correctly when List is Inserted with $compile angularjs angularjs

AngularJS 1.4: Select List Value not Initializing Correctly when List is Inserted with $compile


There seems to be a change in 1.4 related to how the selected option is matched against ngModel by comparing the value attribute in <option value="0"> - it now requires to explicitly use a string to match, rather than allowing for an integer.

In fact, the documentation clearly states:

The value of a select directive used without ngOptions is always a string. When the model needs to be bound to a non-string value, you must either explicitly convert it using a directive ... or use ngOptions to specify the set of options.

To fix, change the initialized value of $scope.curProjID to be a string:

$scope.curProjID = "0"; // instead of $scope.curProjID = 0;

When there is no match (and there isn't, unless you assign a string "0"), select adds an "unknown" option: <option value="? number:0 ?"></option>.


There is another way: using a directive implementing a parser and a formatter. See http://plnkr.co/edit/JZPay8jgm5AXKGXDCjSb

thankx goes to narretz!

Pseudo code:

<select convert-number ng-model="x">   <option value="100">100</option>   <option value="200">200</option></select>app.directive('convertNumber', function() {  return {    require: 'ngModel',    link: function(scope, el, attr, ctrl) {      ctrl.$parsers.push(function(value) {        return parseInt(value, 10);      });      ctrl.$formatters.push(function(value) {        return value.toString();      });          }  }});


I had the same issue. Instead of making sure that my JavaScript code uses string all over the place, I did the following:

Removed the <option ...> items from the HTML file

Introduced a list into JavaScript, similar to:

var orderQuantities = [        { id: 100, text: '100' },        { id: 200, text: '200' },        { id: 300, text: '300' },];

Did make sure that orderQuantities is visible in the scope

Used ng-option in the select tag as follow:

<select ng-model="vm.entity.OrderQuantity" ng-options="orderQuantity.id as orderQuantity.text for orderQuantity in vm.orderQuantities"></select>