I have an enum (I code using TypeScript):
export enum AddressType { NotSet = 0, Home = 1, Work = 2, Headquarters = 3, Custom = -1, }
Then in my controller I have a field named type, into which I set the initial value that should be selected in the select input (I set it to AddressType.Headquarters).
Finally, in my HTML I put the following:
<select ng-model="Ctrl.type" ng-options="addressType for addressType in Ctrl.getAddressTypes()"></select>
Everything seems to work fine except one thing: for some reason Angular does not select "3" (Headquarters) initially in the select after all bindings have been updated. Angular creates an extra option like this instead:
<option value="?" selected="selected"></option>
So for some reason Angular cannot figure the initial option to select in the combo.
If the user selects another option of the combo box, Ctrl.type is updated properly so the binding works fine for that part. Basically my problem is just that the option that should be selected initially is not selected as expected.
What am I missing here that is causing that problem?
In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
I know you're in a hurry for the answer, but a bit of understanding helps. The answer is: (ngModel) causes a 1-way data-binding, whereas [(ngModel)] ensures a two-way data binding.
Found the problem:
The array returned by Ctrl.getAddressTypes() was an array of strings:
["0", "1", "2", "3", "1"]
and what was stored in Ctrl.type was of type number.
AngularJS compares the array supplied to ng-options to the value supplied to ng-model using the '===' operator. 3 does not equal to "3" in that case - that's why it did not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With