Angularjs ng-options using number for model does not select initial value

前端 未结 12 1580
渐次进展
渐次进展 2020-12-01 01:10

I\'m trying to use ng-options with a

提交评论

  • 2020-12-01 01:58

    Very similarly to tymeJV's answer, simple workaround is to convert the default selection number to a string like this:

    self.selectedUnitOrdinal = valueThatCameFromServer.toString();
    

    This way, you don't have to hardcode the number, you can just convert any received value. It's an easy fix without any filters or directives.

    0 讨论(0)
  • 2020-12-01 01:59

    You can also define filter number, this filter will automatically parse string value to int:

    <select ng-model="ctrl.selectedUnitOrdinal" ng-options="unit.id|number as unit.text for unit in ctrl.unitsOptions"></select>
    
    
    angular.module('filters').filter('number', [function() {
            return function(input) {
                return parseInt(input, 10);
            };
        }]);
    
    0 讨论(0)
  • 2020-12-01 02:02

    Angular is seeing your id property as a string, add quotes:

    self.selectedUnitOrdinal = "4";
    
    0 讨论(0)
  • 2020-12-01 02:03

    It's because when you get the unit.id it's returning a string not an integer. Objects in javascript store their keys as strings. So the only way to do it is your approach of surrounding 4 by quotations.

    Edit

    <select ng-model="ctrl.selectedUnitOrdinal" ng-options="convertToInt(unit.id) as unit.text for unit in ctrl.unitsOptions"></select>
    
    $scope.convertToInt = function(id){
        return parseInt(id, 10);
    };
    
    0 讨论(0)
  • 2020-12-01 02:03

    Just to add Christophe's answear: easiest way to achive and maintaint it is to make a directive:

    JS:

    .directive('convertToNumber', function() {
      return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
          ngModel.$parsers.push(function(val) {
            //saves integer to model null as null
            return val == null ? null : parseInt(val, 10);
          });
          ngModel.$formatters.push(function(val) {
            //return string for formatter and null as null
            return val == null ? null : '' + val ;
          });
        }
      };
    });
    

    Christophe's answear wont work correctly for '0' as it returns false on "val?" test.

    0 讨论(0)
  • 提交回复
    热议问题