epv epv - 6 months ago 16
AngularJS Question

Select HTML Value is integer not displaying string

I am running into an issue with a select being displayed

I have a samplemodel value that is an interger in the database. As of right now, I want to do a select as below, but I want it to display the string. The value will be displayed in my two way binding markup but when I select a string of yes, no, or na in the select value, it doesn't display the string or anything at all.

How do I get my value to display the string vs a int.

{{samplemodel}}
<select class="input-large input-large-altered" ng-model="samplemodel">
<option value="1">Yes</option>
<option value="2">No</option>
<option value="3">NA</option>
</select>

Answer

Try using ng-options on your select. You can choose what you would like your model bound to that way.

Example:

 $scope.myArray = [
 {Val: 1, Display: 'Yes'},
 {Val: 2, Display: 'No'},
 {Val: 3, Display: 'NA'}
];
$scope.samplemodel = "Yes";

//Gives the Display string of the object

{{samplemodel}}
    <select class="input-large input-large-altered" ng-options="item.Display as item.Display for item in myArray" ng-model="samplemodel">
    </select>

OR

//Gives the val of the object

 <select class="input-large input-large-altered" ng-options="item.Val as item.Display for item in myArray" ng-model="samplemodel">
    </select>

OR //Gives the whole object

 <select class="input-large input-large-altered" ng-options="item as item.Display for item in myArray" ng-model="samplemodel">
        </select>

Here is the plunkr to give you a full example.

Also to explain ng-options it works like so ng-options="[value] as [display] for [object] in [array]"