在SELECT中的AngularJs – ng-model

的jsfiddle

问题:

我的页面中有一个SELECT元素,用ng-repeat填充。 它也有一个具有默认值的ng-model

当我改变的价值, ng-model适应,没关系。 但是下拉列表在启动时显示一个空的插槽,在那里应该select默认值的项目。

 <div ng-app ng-controller="myCtrl"> <select class="form-control" ng-change="unitChanged()" ng-model="data.unit"> <option ng-repeat="item in units" ng-value="item.id">{{item.label}}</option> </select> </div> 

用JS:

 function myCtrl ($scope) { $scope.units = [ {'id': 10, 'label': 'test1'}, {'id': 27, 'label': 'test2'}, {'id': 39, 'label': 'test3'}, ] $scope.data = { 'id': 1, 'unit': 27 } }; 

你可以在选项元素上使用ng-selected指令。 这需要expression,如果truthy将设置选定的属性。

在这种情况下:

 <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option> 

演示

 angular.module("app",[]).controller("myCtrl",function($scope) { $scope.units = [ {'id': 10, 'label': 'test1'}, {'id': 27, 'label': 'test2'}, {'id': 39, 'label': 'test3'}, ] $scope.data = { 'id': 1, 'unit': 27 } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="myCtrl"> <select class="form-control" ng-change="unitChanged()" ng-model="data.unit"> <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option> </select> </div> 

尝试下面的代码:

在你的控制器中:

  function myCtrl ($scope) { $scope.units = [ {'id': 10, 'label': 'test1'}, {'id': 27, 'label': 'test2'}, {'id': 39, 'label': 'test3'}, ]; $scope.data= $scope.units[0]; // Set by default the value "test1" }; 

在你的页面中:

  <select ng-model="data" ng-options="opt as opt.label for opt in units "> </select> 

工作小提琴

您不需要定义选项标签,您可以使用ngOptions指令来执行此操作: https ://docs.angularjs.org/api/ng/directive/ngOptions

 <select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select> 

但是,ngOptions提供了一些优点,例如通过不为每个重复实例创build新范围来减less内存和提高速度。 angular度文档

另一种解决scheme是使用ng-init指令。 您可以指定将初始化您的默认数据的函数。

 $scope.init = function(){ angular.forEach($scope.units, function(item){ if(item.id === $scope.data.unit){ $scope.data.unit = item; } }); } 

见jsfiddle

你也可以把项目的默认值从ng-repeat中选出来,如下所示:

 <div ng-app="app" ng-controller="myCtrl"> <select class="form-control" ng-change="unitChanged()" ng-model="data.unit"> <option value="yourDefaultValue">Default one</option> <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option> </select> </div> 

不要忘记价值的属性,如果你把它留空,你会有同样的问题。

select的默认值应该是列表中的一个值。 为了加载select默认值,你可以使用ng-options 。 需要在控制器中设置范围variables,并将该variables作为HTMLselect标记中的ng-model进行分配。

查看这个plunker的任何参考:

http://embed.plnkr.co/hQiYqaQXrtpxQ96gcZhq/preview