Angularjs ng-options select as custom object from options array
I am trying to extract 2 different ids from a list of ng-options objects and display them in the selected model when selected by the user. The model displays correctly, but the value does not appear in the 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>
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 }];
});
+3
source to share
1 answer
You are using a very old version of Angular. If you can use a fairly recent version, the answer uses the suggestion track by
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
+7
source to share