AngularJS - 如何在ng-repeat中使用select?

11
在下方提供的视图中,我正在尝试根据当前ng-repeat对象(用户)中可用的键(colorId),在下拉框中选择一个值。 有人知道如何做到这一点吗?
<div ng-app>
  <div ng-controller="MyCntrl">
    <table>
        <thead >
                <tr>
                    <th width="50%">User</th>
                    <th width="50%" >Color</th>            
                </tr>
          </thead>
     <tbody>
         <tr ng-repeat="user in users">
             <td width="50%">{{user.name}}</td>
             <td width="50%"> 
                 <select ng-model="user.colorid" ng-options="color.name for color in colors">
                          <option value="">Select color</option>
        </select>
             </td>
         </tr>  
      </tbody>
    </table>
  </div>
</div>

控制器代码为:

'use strict';

angular.module('nes',)
  .controller('MyCntrl',['$scope',function ($scope) {
   $scope.colors = [
    {id:'1', name:'blue'},
    {id:'2', name:'white'},
    {id:'2', name:'red'}
  ];

    $scope.users = [
        { name:'user1',colorId:'1'},
        { name:'user2',colorId:'2'}
    ];
}]);   
1个回答

23

您需要修复 <select> 元素中的一些问题:

在 ng-options 中使用 color.id as color.name

ng-options="color.id as color.name for color in colors"

您输错了 "colorid":
ng-model="user.colorId"

以下是它正常工作的示例:http://plnkr.co/edit/DptvZuamWv9waFzI0Rcp?p=preview


非常感谢您的快速回复! - Draco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接