2013-07-10 18 views
10

在下面的視圖中,我試圖根據當前ng-repeat對象(用戶)中可用的鍵(colorId)在下拉框中選擇一個值。有誰知道這是怎麼做到的嗎?Angularjs - 如何使用select和ng-repeat?

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

回答

23

你需要修復您的<select>元素的幾件事情:在你的NG選項

使用color.id as color.name

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

你typoed 「colorid」:

ng-model="user.colorId" 

下面是它的工作一個普拉克:http://plnkr.co/edit/DptvZuamWv9waFzI0Rcp?p=preview

+0

非常感謝您的快速反應! –