Combo box binding
Two binding in a drop down
by Bretto
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc9.js"></script>
<script src="http://underscorejs.org/underscore.js"></script>
<div ng-controller="MyCtrl">
<!-- Fill a drop down with the projects ordered by name -->
<select ng-model="selectedProject" ng-options="p.name for p in projects | orderBy: 'name'" ng-required></select>
<hr/>
<!-- Bind the selected projectId to an (hidden) input -->
ProjectID: <input type="text" ng-model="selectedProject.id" value="user.projectId" /> <span>{{selectedProject.name}}</span>
<br />
User Name: <input type="text" value="{{user.name}}" />
<br />
{{arr}}
</div>
JavaScript
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
// This is our list of projects. We don't actually use the description element
$scope.projects= [
{"id": 10, "name": "First Project", "description": "Some description"},
{"id": 20, "name": "Another Project", "description": "Some description"},
{"id": 30, "name": "A really Important Project", "description": "Some description"},
{"id": 40, "name": "An ordinary project", "description": "Some description"}
];
$scope.user={"name": "Peter", "projectId": 30};
// Use underscore _.filter to set currentProject to projectId
$scope.selectedProject = _.filter($scope.projects, function(p){return p.id === $scope.user.projectId})[0];
// NB _.filter returns an array so we just pick the first item
}