AngularJS - Select value returns “? number:x ?” from scope variable

beginer
beginer
1544 Points
52 Posts

I try to bind the select control and select one option through ng-model. It's working fine when the ng-model is non-numeric. But it's not working when it is numeric value. When inspect into the browser it's looks some like

 Team object 

$scope.Teams = [
            {teamId: 10, teamName: 'Camp Gladiator'},
            {teamId: 20, teamName: 'Fit & Fab Moms'},
            {teamId: 30, teamName: 'Steve'},
            {teamId: 40, teamName: 'Jobs'},
            {teamId: 50, teamName: 'Macs'}
        ];

Any help would be greatly appreciated.

Views: 18425
Total Answered: 3
Total Marked As Answer: 1
Posted On: 10-Nov-2017 02:22

Share:   fb twitter linkedin
Answers
Jak
Jak
908 Points
132 Posts
         

If you use Angular 1.6.x, just use the ng-value directive and it will work as expected. My recommendation is to upgrade to 1.6.x.

Posted On: 10-Nov-2017 02:27
Thanks Jak, but I can't upgrade now.
 - beginer  10-Nov-2017 02:30
Smith
Smith
2890 Points
78 Posts
         

For older than 1.6.x create directive to handle it

angular.module('nonStringSelect', [])
.run(function($rootScope) {
  $rootScope.model = { id: 2 };
})
.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;
      });
    }
  };
});

Use it as:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="nonStringSelect">
  <select ng-model="model.Id" convert-to-number>
    <option value="0">Zero</option>
    <option value="1">One</option>
    <option value="2">Two</option>
  </select>
  
  {{ model }}
</div>
Posted On: 10-Nov-2017 02:41
hambi
hambi
56 Points
2 Posts
         

In JS:

module.directive('convertToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(val) {
        return val != null ? parseInt(val, 10) : null;
      });
      ngModel.$formatters.push(function(val) {
        return val != null ? '' + val : null;
      });
    }
  };
});


In HTML:

<select ng-model="model.id" convert-to-number>
  <option value="0">Zero</option>
  <option value="1">One</option>
  <option value="2">Two</option>
</select>
Posted On: 10-Nov-2017 07:13
 Log In to Chat