AngularJS - 使用select /选项嵌套ng-repeat,获取/设置所选值

时间:2016-04-26 17:46:47

标签: javascript angularjs drop-down-menu angularjs-ng-repeat

我正在尝试设置两个ng-repeat循环,其中一个是嵌套的循环,是一个select / option下拉。我检查了其他类似的帖子,但仍不确定如何在HTML中定义ng-model以获取/设置选择框中的默认值/选项。

    <table>
      <tr ng-repeat="student in studentList">
        <td>{{student.name}}</td>
        <td>
          <select ng-model="courseSelected">
            <option ng-repeat="course in courseList" value="{{course.id}}">{{course.name}}</option>
          </select>
        </td>
      </tr>
   </table>

studentList和courseList都来自数据库表,student表/对象有一个courseId列/引用。换句话说,默认选择的课程和更改的课程选项(如果发生这种情况)将具有其背后的逻辑:student.courseId = course.id

感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

<select ng-model="student.courseId" ng-options="course.name as course.id for course in courseList">

这应该可以帮到你找到你想要的东西。我假设课程有name属性。但您可以使用ng-options指令中的任何属性为该课程添加别名。可以找到更多文档here

答案 1 :(得分:0)

我认为你应该在标签中使用ng-options:

<select ng-model="courseSelected" ng-options= "course.id for course in courseList">

也许您应该阅读这些文档以获得更多解释:

https://docs.angularjs.org/api/ng/directive/ngOptions

https://docs.angularjs.org/api/ng/directive/select

答案 2 :(得分:0)

var editer = angular.module('app', []);

function myCtrl($scope) {

  $scope.studentList = [{
    id: 1,
    name: 'Jack'
  }, {
    id: 2,
    name: 'Terry'
  }, {
    id: 3,
    name: 'Rosa'
  }, {
    id: 4,
    name: 'Holt'
  }];
  $scope.courseList = [{
    id: 1,
    name: 'Course1'
  }, {
    id: 2,
    name: 'Course2'
  }];

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 
<div ng-app="app" ng-controller="myCtrl" class="container">
<table>
      <tr ng-repeat="student in studentList">
        <td>{{student.name}}</td>
        <td>
          <select ng-model="student.courseSelected" ng-options="course as course.name for course in courseList">
    </select>
         
        </td>
        <td>
          {{student.courseSelected.name}}
          </td>
      </tr>
   </table>
  <label class="item item-input">
    <span class="input-label">Select date</span>
    
  </label>

  <pre>{{dateOption}}</pre>
</div>