Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to fetch 2 different ids from ng-options object list and map the same into select model on user select. The model is mapped properly but the value is not shown on select box.

http://plnkr.co/edit/Z3ohLie4vpTvXhUiLfl6?p=preview

<!DOCTYPE html>
    <html ng-app="angularjs-starter">

      <head lang="en">
        <meta charset="utf-8">
        <title>Custom Plunker</title>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
        <link rel="stylesheet" href="style.css">
        <script src="app.js"></script>
      </head>

      <body ng-controller="MainCtrl">
        <h1>Select something</h1>
        <select ng-model="selectedItem" ng-options="{'id':item.id,'anotherid':item.anotherId} as item.name for item in items"></select>
        <h3>The selected item:</h3>
        <pre>{{selectedItem | json}}</pre>
      </body>

    </html>

The Javascript:

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    { id: 1, name: 'foo', anotherId: 11 },
    { id: 2, name: 'bar', anotherId: 22 },
    { id: 3, name: 'blah', anotherId: 33 }];
});
share|improve this question

1 Answer 1

up vote 4 down vote accepted

You are using a very old version of Angular. If you can use a fairly recent version, the answer is using the track by clause of ng-options:

<select ng-model="selectedItem"
  ng-options="{'id':item.id,'anotherid':item.anotherId} as item.name for item in items track by item.id"></select>

Forked plunk: http://plnkr.co/edit/0SwHfYVuYd5iIA9P4mpU?p=preview

share|improve this answer
1  
I really don't understand why simple select is so complicated. Anyways +1 for right answer but I would try to find out more simple solution :) –  Maxim Shoustin Aug 6 '14 at 19:10
    
I agree that the comprehension stuff in selects is overly complicated and underly explained. –  Dan Doyon Aug 6 '14 at 19:29
    
and again ng-options="{'a':item.id,'b':item.anotherId} as item.name for item in items track by item.id" would not work. Confused –  WiseWins Aug 6 '14 at 19:34
    
Figured it out myself - {'id':item.id,'fgdfg':item.anotherId}. key for the first element in custom object must match the ng-options objects' identifier. oh a little tricky –  WiseWins Aug 6 '14 at 19:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.