3

I will be getting the selected value as integer from service and need to send it back as integer. please check the Plnkr for code

<!-- Working -->
<div ng-init="selectedvalue = '3'">
    <select ng-model="selectedvalue">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
</div>
<!-- Not Working -->
<div ng-init="selectedvalue2 = 3">
    <select ng-model="selectedvalue2">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>
</div>
<!-- Not Working -->
<div ng-init="selectedvalue3 = 3">
    <select ng-model="selectedvalue3">
    <option value=1>1</option>
    <option value=2>2</option>
    <option value=3>3</option>
    <option value=4>4</option>
  </select>
</div>

https://plnkr.co/edit/R7QfJfy6m6IgHKL07tFI?p=preview

neevany
  • 128
  • 7

4 Answers4

3

in ng-model you can add a filter number to convert like this:

ng-model="selectedvalue3 | number"
Brahim LAMJAGUAR
  • 1,254
  • 5
  • 19
  • 28
1

you can follow this process select as label for value in array and better way to initialize value from controller.

Like in controller :

$scope.selectedvalue3 = 30;
$scope.infos= [{age:21, name:"xx"},{age:20, name:"yyy"},{age:30, name:"zzz"},{age:40, name:"ppp"}];

and in HTML:

<div>
     <select ng-options="info.age as info.age for info in infos" ng-model="selectedvalue3"></select>
</div>

where age is integer value . it may help you

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
0

The value in select are interpreted like string.

You must work with string and convert/parse your value after or before.

Alexis
  • 5,681
  • 1
  • 27
  • 44
0

Add a directive to parse string to int. e.g. convert-to-number on your select tag:

<select ng-model="selectedvalue" convert-to-number>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Then you can have

.directive('convertToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(val) {
        return parseInt(val, 10);
      });
      ngModel.$formatters.push(function(val) {
        return '' + val;
      });
    }
  };
});
mws777
  • 16
  • 3