0

I'm trying to use ng-options with a to bind a numeric integer value to a list of corresponding options:

angular.module('nonStringSelect', [])
.controller('MyCtrl', function($scope) {
  $scope.loadedModels = [
    {
      id_category: 1,
      title: 'Category A',
    },
    {
      id_category: 2,
      title: 'Category B',
    },
    {
      id_category: 3,
      title: 'Category C',
    },
  ];
  $scope.model = 3;
})
.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;
      });
    }
  };
});

HTML:

<body ng-app="nonStringSelect" ng-controller="MyCtrl">
  <select ng-model="model" ng-options="item.title for item in loadedModels track by item.id_category" convert-to-number>
</select>
{{ model }}
</body>

At first, I tried using

<select ng-model="model" ng-options="item.id_category as item.title for item in loadedModels" convert-to-number>

but it produced

<option value="number:1" label="Category A">Category A</option>

Now I use

ng-options="item.title for item in loadedModels track by item.id_category"

and it generated the correct options:

<option value="1" label="Category A">Category A</option>

I tried to follow the answer described here but it doesn't work. When the page is loaded no item is selected in the list and whenever I select any item the model becomes NaN.

Here is a plnkr.

Community
  • 1
  • 1
user2513149
  • 850
  • 12
  • 15
  • `value="number:1"` precisely shows that the select is bound to a numeric value in the scope. http://plnkr.co/edit/qwdW0xfKOJX0aEntLmzz?p=preview – JB Nizet Jun 19 '16 at 17:51
  • @JB Nizet, yes, but when I try to save the model to database it gives me validation error that the value is not valid integer, since string "number:1" cannot be converted to int. – user2513149 Jun 19 '16 at 18:28
  • Well, you're not supposed to submit the form directly. You're supposed to call a method ofyour controller that uses $http to post the bound data as JSON. That's how angular is designed to work. – JB Nizet Jun 19 '16 at 18:32
  • But still I need the dropdown to show a pre-selected item when the page is loaded. – user2513149 Jun 19 '16 at 18:39

0 Answers0