0

I have a select which I render like this:

<select
    ng-model="otherDoc.sub_category"
    ng-options="key as value for (key, value) in vm.otherDocs"
>
</select>

otherDoc.sub_category is a number however, the select converts the value into string. So they does not match.

how can I tell angular to match the model for content and not for type?

Pablo
  • 9,424
  • 17
  • 55
  • 78
  • 1
    This is mentioned in [the documentation for `select`](https://docs.angularjs.org/api/ng/directive/select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting) – Heretic Monkey Jan 04 '17 at 19:56

1 Answers1

2

The trick is using ngModel.$parsers and ngModel.$formatters

If I understand you, you want the value coming back from the select to be translated back into a number before it hits the model (otherDoc.sub_category).

I would add a directive to your select like so

(The HTML)

<select 
    ng-model="otherDoc.sub_category
    ng-options="key as value for (key, value) in vm.otherDocs"
    formatter-directive>
</select>

(The Javascript)

angular.module('someModuleName').directive('formatterDirective', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$formatters.push(function(val) {
          return parseInt(val, 10);
      });
    }
  };
});

The value in your model will be parsed into a base 10 integer when it comes back from the view.

Chris Noel
  • 36
  • 1
  • Also this is a good article on formatters and parsers -https://alexperry.io/angularjs/2014/12/10/parsers-and-formatters-angular.html – Chris Noel Jan 04 '17 at 20:48