0

I have a list of items, each has its own item.value and item.name. I want to generate HTML code as follows:

<option value="{{item.value}}">{{item.name}}</option>

how can I do it in AngularJS? Thanks a lot.

UPDATE: I forget to mention the list I have is an object because I want to associate the Id to use it as an index, for e.g.:

$scope.list={
    0:{value:0,name:"name0"},
    5:{value:5,name:"name5"}
}
boh
  • 1,477
  • 2
  • 16
  • 35
  • 2
    possible duplicate of [AngularJS - How can I reference the property name within an ng-Repeat](http://stackoverflow.com/questions/10954286/angularjs-how-can-i-reference-the-property-name-within-an-ng-repeat) – Stewie Jun 03 '13 at 04:46
  • 3
    Use `ng-options` instead of `ng-repeat` when using selects - http://stackoverflow.com/questions/13803665/angularjs-value-attribute-for-select – Dan Jun 03 '13 at 05:00
  • yes I have tried those methods but didn't know why they didn't work for me, then I just realized that I have an object containing all items, not an array. Please check my update. – boh Jun 03 '13 at 06:43

2 Answers2

4
function Ctrl($scope) {  
  $scope.list={
      0:{value:0,name:"name0"},
      5:{value:5,name:"name5"}
  }
}

Along with:

<select>
  <option ng-repeat="item in list" value="{{item.value}}">{{item.name}}</option>
</select>

Working: http://plnkr.co/edit/7ueudpXuGwmQt627fZGE?p=preview

basarat
  • 261,912
  • 58
  • 460
  • 511
  • the list I have is an object, sorry for not mentioning that: `$scope.list={ 0:{value:0,name:"asdf"}, 1:{value:1,name:"bsdf"} }` – boh Jun 03 '13 at 06:39
  • 1
    Works with that as well :http://plnkr.co/edit/7ueudpXuGwmQt627fZGE?p=preview since the for iterates over every key property. Doesn't matter if its a list or obj. – basarat Jun 03 '13 at 06:47
  • ahh, there is a typo in the key name and thus obj.key returns undefined, so Angular evals the expression as an empty string. Thanks a lot. – boh Jun 03 '13 at 07:04
2

Using ng-options with your object model:

<select ng-options="v.value as v.name for (k,v) in list" ng-model="selected">
  <option value="">select a value</option>
</select>
<div>{{selected}}</div>

Your model:

function Ctrl($scope) {  
    $scope.list={
      0:{value:0,name:"name0"},
      5:{value:5,name:"name5"}
  }
}

Working Example: http://plnkr.co/edit/uNJXlCObZdhT96YDje5p?p=preview

basarat
  • 261,912
  • 58
  • 460
  • 511