以下是困扰很多人(包括我)的问题。

当在AngularJS中使用ng-options指令来填充<select>标记的选项时,我不知道如何为一个选项设置值。这方面的文档确实不清楚——至少对我这样的傻瓜来说是这样。

我可以像这样轻松地设置一个选项的文本:

ng-options="select p.text for p in resultOptions"

例如,当resultOptions为:

[
    {
        "value": 1,
        "text": "1st"
    },
    {
        "value": 2,
        "text": "2nd"
    }
]

它应该是(可能是)设置选项值最简单的事情,但到目前为止,我只是不明白它。


当前回答

See ngOptions ngOptions(optional) – {comprehension_expression=} – in one of the following forms: For array data sources: label for value in array select as label for value in array label group by group for value in array select as label group by group for value in array track by trackexpr For object data sources: label for (key , value) in object select as label for (key , value) in object label group by group for (key, value) in object select as label group by group for (key, value) in object

对你来说,应该是

array = [{ "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" }];

<select ng-options="obj.value as obj.text for obj in array"></select>

更新

随着AngularJS的更新,现在可以用track by表达式为select element的value属性设置实际值了。

<select ng-options="obj.text for obj in array track by obj.value">
</select>

如何记住这些丑陋的东西

对于那些很难记住这种语法形式的人:我同意这不是最简单或最漂亮的语法。这种语法是Python列表推导式的扩展版本,知道这一点有助于我很容易地记住语法。大概是这样的:

Python代码:

my_list = [x**2 for x in [1, 2, 3, 4, 5]]
> [1, 4, 9, 16, 25]

# Let people to be a list of person instances
my_list2 = [person.name for person in people]
> my_list2 = ['Alice', 'Bob']

这实际上与上面列出的第一个语法相同。但是,在<select>中,我们通常需要区分代码中的实际值和<select>元素中显示的文本(标签)。

比如,我们需要人手。Id,但我们不想把Id显示给用户;我们想要显示它的名字。同样,我们对代码中的person.name不感兴趣。这里有as关键字来标记东西。所以它变成了这样:

person.id as person.name for person in people

或者,代替person。Id我们可能需要person实例/引用本身。见下文:

person as person.name for person in people

对于JavaScript对象,同样的方法也适用。只需要记住,对象中的项是用(key, value)对解构的。

其他回答

我也有这个问题。我不能在ng-options中设置我的值。生成的每个选项都设置为0,1,…, n。

为了让它正确,我在ng-options中做了这样的事情:

HTML:

<select ng-options="room.name for room in Rooms track by room.price">
    <option value="">--Rooms--</option>
</select>

我使用“track by”来设置所有的room.price值。

(这个例子很糟糕:因为如果有多个价格相等,代码就会失败。所以一定要有不同的值。)

JSON:

$scope.Rooms = [
            { name: 'SALA01', price: 100 },
            { name: 'SALA02', price: 200 },
            { name: 'SALA03', price: 300 }
        ];

我从一篇博客文章中学会了如何使用Angular.JS ng-options & track by设置一个选择元素的初始选择值。

观看视频。这是一个很好的类:)

在ng-options中选择一个项目可能有点棘手,这取决于您如何设置数据源。

在与它们斗争了一段时间后,我最终用我使用的最常用的数据源制作了一个样本。你可以在这里找到它:

http://plnkr.co/edit/fGq2PM?p=preview

现在要让ng-options工作,需要考虑以下几点:

Normally you get the options from one source and the selected value from other. For example: states :: data for ng-options user.state :: Option to set as selected Based on 1, the easiest/logical thing to do is to fill the select with one source and then set the selected value trough code. Rarely would it be better to get a mixed dataset. AngularJS allows select controls to hold more than key | label. Many online examples put objects as 'key', and if you need information from the object set it that way, otherwise use the specific property you need as key. (ID, CODE, etc.. As in the plckr sample) The way to set the value of the dropdown/select control depends on #3, If the dropdown key is a single property (like in all examples in the plunkr), you just set it, e.g.: $scope.dropdownmodel = $scope.user.state; If you set the object as key, you need to loop trough the options, even assigning the object will not set the item as selected as they will have different hashkeys, e.g.: for (var i = 0, len = $scope.options.length; i < len; i++) { if ($scope.options[i].id == savedValue) { // Your own property here: console.log('Found target! '); $scope.value = $scope.options[i]; break; } }

您可以在另一个对象$scope.myObject.myProperty中替换相同属性的savedValue。

今天我已经为这个问题纠结了一段时间。我通读了AngularJS的文档,这篇文章和其他一些文章,还有一些它们指向的博客。他们都帮助我理解了更细微的细节,但最终这似乎是一个令人困惑的话题。主要是因为ng-options的许多语法细微差别。

最后,对我来说,它归结为少即是多。

给定一个作用域,配置如下:

        //Data used to populate the dropdown list
        $scope.list = [
           {"FirmnessID":1,"Description":"Soft","Value":1},         
           {"FirmnessID":2,"Description":"Medium-Soft","Value":2},
           {"FirmnessID":3,"Description":"Medium","Value":3}, 
           {"FirmnessID":4,"Description":"Firm","Value":4},     
           {"FirmnessID":5,"Description":"Very Firm","Value":5}];

        //A record or row of data that is to be save to our data store.
        //FirmnessID is a foreign key to the list specified above.
        $scope.rec = {
           "id": 1,
           "FirmnessID": 2
        };

这就是我想要得到的结果:

        <select ng-model="rec.FirmnessID"
                ng-options="g.FirmnessID as g.Description for g in list">
            <option></option>
        </select>   

注意,我没有使用track by。使用所选项的跟踪将总是返回与FirmnessID匹配的对象,而不是FirmnessID本身。这现在满足了我的标准,即它应该返回一个数值而不是对象,并且使用ng-options来获得它所提供的性能改进,而不是为生成的每个选项创建一个新的作用域。

同样,我需要空白的第一行,所以我简单地在<select>元素中添加了一个<option>。

这是一个展示我作品的Plunkr。

对我来说,布鲁诺·戈麦斯的答案是最好的答案。

但实际上,您不需要担心设置select options的value属性。AngularJS会处理这个。让我详细解释一下。

请考虑这把小提琴

angular.module('mySettings', []).controller('appSettingsCtrl', function ($scope) {

    $scope.timeFormatTemplates = [{
        label: "Seconds",
        value: 'ss'
    }, {
        label: "Minutes",
        value: 'mm'
    }, {
        label: "Hours",
        value: 'hh'
    }];


    $scope.inactivity_settings = {
        status: false,
        inactive_time: 60 * 5 * 3, // 15 min (default value), that is, 900 seconds
        //time_format: 'ss', // Second (default value)
        time_format: $scope.timeFormatTemplates[0], // Default seconds object
    };

    $scope.activity_settings = {
        status: false,
        active_time: 60 * 5 * 3, // 15 min (default value), that is,  900 seconds
        //time_format: 'ss', // Second (default value)
        time_format: $scope.timeFormatTemplates[0], // Default seconds object
    };

    $scope.changedTimeFormat = function (time_format) {
        'use strict';

        console.log('time changed');
        console.log(time_format);
        var newValue = time_format.value;

        // do your update settings stuffs
    }
});

正如你在fiddle输出中看到的,无论你为选择框选项选择了什么,它都是你的自定义值,或者AngularJS自动生成的0、1、2值,这在你的输出中并不重要,除非你使用jQuery或任何其他库来访问选择组合框选项的值并相应地操作它。

value属性如何获取其值:

当使用数组作为数据源时,它将是数组元素在每次迭代中的索引; 当使用对象作为数据源时,它将是每次迭代中的属性名。

所以在你的例子中,它应该是:

obj = { '1': '1st', '2': '2nd' };

<select ng-options="k as v for (k,v) in obj"></select>