【问题标题】:AngularJS: Select with ng-options- how to pass value as integer?AngularJS:使用 ng-options 选择 - 如何将值作为整数传递?
【发布时间】:2016-02-13 11:32:35
【问题描述】:

我的选择表单有问题。当我选择任何选项时,传递的值是字符串类型,而不是数字类型。这是我用于 ng-repeat 的对象:

$scope.apples ={
         0:'Apple0',
         1:'Apple1',
         2:'Apple2',
         3:'Apple3'
};

这是我的选择,它传递的是字符串,而不是数字:

 <select ng-model="test" ng-options="key as value for (key,value) in apples"></select>

有什么想法吗?

【问题讨论】:

    标签: angularjs select ng-options


    【解决方案1】:

    每次迭代对象字段时,IMO,都会出现设计问题。使用数组:

    $scope.apples = [
      {
        id: 0,
        name: 'Apple0'
      },
      {
        id: 1,
        name: 'Apple1'
      },
      ...
    ];
    

    在视图中:

    ng-options="apple.id as apple.name for apple in apples"
    

    【讨论】:

    • 那行得通。我知道这不是主题,但你能解释一下这种设计与原始设计相比有什么好处吗?
    • 顺序是可预测的,而在使用对象时则不是。您可以对数组进行排序(按 ID 或更实际地按名称):apple.id as apple.name for apple in apples | orderBy:'name'。
    • 这是有道理的。谢谢!
    【解决方案2】:

    非常简单的方法是将字符串实际转换为数字(注意,+ 运算符):

    ng-options="+key as value for (key,value) in apples"
    

    也可以使用数组作为数据结构:

    $scope.apples = [
        'Apple0',
        'Apple1',
        'Apple2',
        'Apple3'
    ];
    

    然后

    ng-options="apples.indexOf(apple) as apple for apple in apples"
    

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      相关资源
      最近更新 更多