选择在ng-options填充时覆盖的默认选项


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

我有一个选择下拉在我的代码。这些选项是通过RESTful数据库调用填充的。当从数据库检索结果时,下拉框中显示的值被设置为student字段中的第一个值。

我怎样才能使禁用值是一个显示,直到用户实际单击下拉菜单并选择一个?

试试这个:

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

所以我假设你有一个函数,返回学生,然后你分配学生范围…?

在给student分配作用域之前将默认选项压入student数组

$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。和做。

最新更新