ThisLanham ThisLanham - 4 months ago 16
AngularJS Question

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

Here's some quick background info. I just upgraded to Angular 1.4. I'm using an API written in C# for my server-side calls.

A section of my page shows 2 select lists (Project & Sub-project). Both are supposed to default to "(Select a ______)", which I list as the first option of each select with "value" of 0. The appropriate ng-model variables are initialized to 0.

The actual HTML code for the select lists is being generated on the server side using string concatenation, passed to the client via $http, and inserted using a directive that calls $compile (not ideal at all, but my client has pretty much chained me to this API). Prior to the 1.4 update, everything was working nicely.

Now, my Project select list is defaulting to nothing. When I inspect the element, this is what I see...

<select ng-change="updateSubProjList()" ng-model="curProjID">
<option value="? number:0 ?"></option>
<option value="0">(Select a Project)</option>
<option value="1">First Project</option>
<option value="2">Second Project</option>
...
</select>


...with that first "? number:0 ?" entry being the one that is currently selected. My Sub-project select list still initializes just fine, which makes this even more odd.

I know that there were some updates to $compile in the update to AngularJS 1.4, but I can't figure out a solution to my problem. Any assistance would be greatly appreciated.

Answer

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>.

Comments