【问题标题】:Angularjs ng-options for an objectAngularjs ng-options 对象
【发布时间】:2014-04-14 04:41:40
【问题描述】:

我有一个表格,用于收集歌手的名字和姓氏、2 位吉他手的名字和姓氏以及鼓手的名字和姓氏等信息。我正在尝试使用 ng-options 将这些值推送到 select 标记中。

我可以成功地让吉他手的名字出现在选择下拉菜单中,但我似乎无法让歌手和鼓手出现。

<select ng-model="band" ng-options="band.firstName for firstName in band"></select>

$scope.band = {"singer": {
  "firstName": "Dave",
  "lastName": "Grohl"
  },"guitarists": [
{
  "firstName": "Chris",
  "lastName": "Shiflett"
},
{
  "firstName": "Pat",
  "lastName": "Smear"
}],"drummer": {
"firstName": "Taylor",
"lastName": "Hawkins" }};

这是一个小提琴:http://jsfiddle.net/rfT7f/17/

任何见解将不胜感激。

【问题讨论】:

    标签: angularjs ng-options


    【解决方案1】:

    使用ngOptions,您必须使用一致的对象(或数组)结构,例如

    $scope.band = [
        {
          "firstName": "Dave",
          "lastName": "Grohl",
          "role": "singer"
        },
        {
          "firstName": "Chris",
          "lastName": "Shiflett",
          "role": "guitarist"
        },
        {
          "firstName": "Pat",
          "lastName": "Smear",
          "role": "guitarist"
        },
        {
          "firstName": "Taylor",
          "lastName": "Hawkins",
          "role": "drummer"
        }
    ];
    

    然后你可以在你的选择中做一些很酷的事情,比如将选项组合在一起:

    <select ng-model="bandMember"
        ng-options="artist.firstName group by artist.role for artist in band">
    </select>
    

    编辑:

    忘记提及您的ngModel 应该指向您要存储所选选项的位置,在本例中为 $scope.bandMember

    【讨论】:

    • 不幸的是,这是我必须使用的结构。是否可以将每个人的名字和姓氏复制到另一个数组中?并改用它?
    • 当然,使用 lodash 或下划线,将其添加到您的控制器:$scope.artistList = []; _.each($scope.band, function(artist, role) { if (_isArray(artist)) { _.each(artist, function(member){ $scope.artistList.push(member);}); } else { $scope.artistList.push(artist) } }); 然后使用 artistList 作为您的 ng-options
    • 我正在尝试实现这一点,但它不合作。我添加了下划线,但仍然出现错误。jsfiddle.net/K94Hz/1
    • 两件事,我的代码中缺少.,应该是_.isArray,而您忘记将您的选择标签更新为&lt;select ng-model="bandMember" ng-options="artist.firstName for artist in artistList"&gt;&lt;/select&gt;jsfiddle.net/K94Hz/3
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多