Search code examples
javascriptangularjsngmodel

Angular: ng-model as a number


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?


Solution

  • 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.