JAVAScript/Answer Detail

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

beginer
beginer
48 Points
19 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.

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

Share:   fb twitter linkedin
Answers
Jak
Jak
Member
348 Points
149 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
306 Points
98 Posts
Marked as answer      

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
10 Points
5 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

Blog

Active User (0)

No Active User!
 Log In to Chat