Angular select - 根据属性

时间:2017-03-16 23:54:25

标签: angularjs select properties initialization

我有一系列的主题,如:

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

还有一系列老师:

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

我需要创建一个表单,我将在其中生成一个主题列表,每个主题都有一个下拉列表(select),允许选择首选教师。 但是,我不知道如何使用Angular选项初始化的每个(!)选择显示当前选择的首选教师。

我们将非常感谢任何帮助 - 我未能对我的案件应用其他答案。

编辑:

添加了属性_id以反映我的特定情况

1 个答案:

答案 0 :(得分:1)

试试这个(根据OP编辑更新):



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>
&#13;
&#13;
&#13;

如果您有任何问题,请与我们联系。