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'}
    ];
}]);   
4

1 回答 1

23

您需要修复<select>元素中的一些内容:

color.id as color.name在您的 ng 选项中使用。

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

你打错了“colorid”:

ng-model="user.colorId"

这是它的工作原理:http ://plnkr.co/edit/DptvZuamWv9waFzI0Rcp?p=preview

于 2013-07-10T15:05:58.713 回答