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

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

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

提交评论

  • 2020-12-01 01:48

    While the solution provided by Mathew Berg works it will probably break other selects that use sting-valued select options. This may be a problem if you try to write one universal directive for handling selects (like I did).

    A nice workaround is to check if the value is a number (even if it is a string containing a number) and only than do the conversion, like so:

    angular.module('<module name>').filter('intToString', [function() {
            return function(key) {
                return (!isNaN(key)) ? parseInt(key) : key;
            };
        }]);
    

    or as a controller method:

    $scope.intToString = function(key) {
        return (!isNaN(key)) ? parseInt(key) : key;
    };
    
    0 讨论(0)
  • 2020-12-01 01:52

    Make id property in unitsOptions as number

    self.unitsOptions = Object.keys(unitOptionsFromServer).map(function (key) {
            return { id: +key, text: unitOptionsFromServer[key] };
        });
    

    http://jsfiddle.net/htwc10nx/

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

    I think the other solutions are overly complex for simply establishing the value as an integer. I would use:

    <select ng-model="model.id">
        <option ng-value="{{ 0 }}">Zero</option>
        <option ng-value="{{ 1 }}">One</option>
        <option ng-value="{{ 2 }}">Two</option>
    </select>
    
    0 讨论(0)
  • 2020-12-01 01:57
    <select ng-model="ctrl.selectedUnitOrdinal" ng-options="+(unit.id) as unit.text for unit in ctrl.unitsOptions"></select>
    
    0 讨论(0)
  • 2020-12-01 01:57

    You can use ng-value attribute. Like this:

    <select ng-model="model.id">
      <option ng-value="0">Zero</option>
      <option ng-value="1">One</option>
      <option ng-value="2">Two</option>
    </select>

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