angular 的 select 中 ng-options 设置默认值

angular 的 select 中 ng-options 设置默认值

在AngularJS 开发的后台web系统中,经常需要对后台数据进行修改,而在修改数据的过程中,若页面中有select下拉框,需要让其选中原来的数据,即select中需要设置默认值。

默认值设置方法:

  1. 在select中使用ng-model绑定数据myColor,

  2. 在对应的controller中定义ng-model全局数据$scope.myColor,并为其赋值,该值即为select的默认值。

代码如下:

angular.module('myApp', [])
  .controller('MyController', ['$scope'], function($scope) {
    $scope.colors = ['black', 'white', 'red', 'blue', 'yellow'];
    
    $scope.myColor = $scope.colors[2];
  })
<div ng-controller="MyController">
  <select ng-model="myColor" ng-options="color for color in colors"></select>
</div>

显示效果:
图片描述

说明: 该文档参考angular官方api

评论

暂无评论