JAVA Script/Answer Detail

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

beginer
18 Points
9 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: 0
Posted On: 10-Nov-2017 02:22
Answers
Jak
Member
332 Points
146 Posts
 
 
Posted On: 10-Nov-2017 02:27

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.

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

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>
hambi
6 Points
3 Posts
 
 
Posted On: 10-Nov-2017 07:13

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>

When replying / answering a question please:

  1. Read the question and other answers carefully.
  2. Understand that English isn't everyone's first language so be sympathetic of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for explanation, ignore it. rudeness is not allowed.
Let's work to help programmers, not make them feel stupid.

Blog

Active User (2)

 Log In to Chat