HTML Select 填充 ng-options 时覆盖默认选项

HTML Select default option overriden when ng-options is populated

<select ng-model="grade.students" ng-options="st as st.name for st in students">
          <option disabled selected value > -- Select a Student --</option>
</select>

我的代码中有一个 select 下拉菜单。这些选项是从 RESTful 数据库调用中填充的。从数据库中检索结果时,下拉列表中显示的值设置为学生中的第一个值。

如何使禁用值成为在用户实际单击下拉菜单之前显示的值和 selects 值?

试试这个:

var student1 = {
    id: 1,
    name: 'cool guy'
}
var student2 = {
    id: 2,
    name: 'nerd'
}
var students = [student1, student2];

所以我假设你有一个 returns 学生的功能,然后你将学生分配到范围...?

在将学生分配到范围之前,将默认选项推送到学生数组

$scope.selectedStudent = 0;
students.push({ id: 0, name: 'select one' });
$scope.students = students;

然后您将设置一个函数以在选择学生时调用

$scope.someFunction = function (student) {
    // do something with the selected student
}

现在在你的 html 中你会得到这样的东西:

<select ng-model="selectedStudent" ng-options="st.id as st.name for st in students" ng-change="someFunction(st)"></select>

如果稍后您决定预选学生,只需将 $scope.selectedStudent 设置为学生的 ID。完成了。