使用数量模型Angularjs NG选项没有选择初始值 [英] Angularjs ng-options using number for model does not select initial value

查看:177
本文介绍了使用数量模型Angularjs NG选项没有选择初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用NG选项以<选择> 为数字整数值绑定到相应的选项列表。在我的控制器,我有这样的事情:

I'm trying to use ng-options with a <select> to bind a numeric integer value to a list of corresponding options. In my controller, I have something like this:

myApp.controller('MyCtrl', function() {
    var self = this;

    var unitOptionsFromServer = {
        2: "mA",
        3: "A",
        4: "mV",
        5: "V",
        6: "W",
        7: "kW"
    };

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

    self.selectedUnitOrdinal = 4; // Assume this value came from the server.
});

HTML

<div ng-controller="MyCtrl as ctrl">
    <div>selectedUnitOrdinal: {{ctrl.selectedUnitOrdinal}}</div>
    <select ng-model="ctrl.selectedUnitOrdinal" ng-options="unit.id as unit.text for unit in ctrl.unitsOptions"></select>
</div>

和这里的的jsfiddle 展示的问题,我已经采取了,但我并不快乐与其他一些方法。

And here's a jsFiddle demonstrating the problem, and some other approaches I've taken but am not happy with.

select选项将被用空值进行初始化,而不是MV如预期在这个例子中。结合似乎很好地工作,如果你选择不同的选项 - selectedUnitOrdinal更新正确

The select option is being initialized with an empty value, instead of "mV" as expected in this example. The binding seems to work fine if you select a different option -- selectedUnitOrdinal updates properly.

我已经注意到,如果初始模型值设置为一个字符串,而不是一个数字,那么初始选择的作品(见#3小提琴)。

I've noticed that if you set the initial model value to a string instead of a number, then the initial selection works (see #3 in the fiddle).

我真的想NG-选项发挥好与数字选项值。我怎样才能优雅地做到这一点?

I really would like ng-options to play nice with numeric option values. How can I achieve this elegantly?

推荐答案

这是因为当你得到unit.id它返回一个字符串不是整数。在JavaScript对象存储他们的密钥为字符串。因此,要做到这一点的唯一方法是通过你周围的报价4的方法。

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.

修改

<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);
};

这篇关于使用数量模型Angularjs NG选项没有选择初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆