Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - how to use select with ng-repeat?

Tags:

angularjs

In the view available below I'm trying to select a value in the drop down box based on a key(colorId) available in the current ng-repeat object(user). Does anyone know how to do that?

<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>

The controller code is:

'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'}
    ];
}]);   
like image 862
gelu gara Avatar asked Jul 10 '13 15:07

gelu gara


1 Answers

You need to fix a few things in your <select> element:

use color.id as color.name in your ng-options.

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

you typoed "colorid":

ng-model="user.colorId"

Here's a plunk of it working: http://plnkr.co/edit/DptvZuamWv9waFzI0Rcp?p=preview

like image 165
Ben Lesh Avatar answered Oct 20 '22 18:10

Ben Lesh