tonysepia
tonysepia

Reputation: 3510

Angular select - make option selected based on property

I have an array of subjects like:

`[
  { subject: 'Maths',   preferred_teacher: '00000'},
  { subject: 'Chemistry',   preferred_teacher: '11111'},
  { subject: 'Art',   preferred_teacher: ''}
]`

And an array of teachers:

[{name:'Farmer', _id: '00000'},{name:'Smith', _id: '11111'}]

I need to create a form, where I will produce a list of subjects with a dropdown (select) for each one, allowing to pick the preferred teacher. However, I don't know how I can make each (!) select initialized with Angular options show the presently selected preferred teacher.

Any help would be greatly appreciated - I have failed to apply other answers to my case.

EDIT:

Added property _id to reflect my particular case

Upvotes: 1

Views: 66

Answers (1)

Tim Harker
Tim Harker

Reputation: 2417

Try this (updated based on OP edit):

var app = angular.module('app', []);
app.controller('MainCtrl', ['$scope',
  function($scope) {
    $scope.subjects = [
      {subject: 'Maths', preferred_teacher: '00000'},
      {subject: 'Chemistry', preferred_teacher: '11111'},
      {subject: 'Art', preferred_teacher: ''}
    ];
    $scope.teachers = [{name:'Farmer', _id: '00000'}, {name:'Smith', _id: '11111'}];
  }
]);
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
  <form>
    <table>
      <tr>
        <th>Subject</th>
        <th>Teacher</th>
      </tr>
      <tr ng-repeat="subject in subjects">
        <td><span ng-bind="subject.subject"></span></td>
        <td><select ng-model="subject.preferred_teacher"
                    ng-options="teacher._id as teacher.name for teacher in teachers">
            </select></td>
      </tr>
    </table>
    <br> {{subjects}}
  </form>
</div>

Let me know if you have any questions.

Upvotes: 1

Related Questions