2016-07-25 57 views
3

我有一个下拉列表的结果列表。在Angular JS中设置选定的下拉选项

<div ng-app="myApp" ng-controller="myCtrl"> 

<select ng-model="selectedName" ng-options="item.value for item in names track by item.id"> 
</select> 

</div> 

<script> 
var app = angular.module('myApp', []); 
app.controller('myCtrl', function($scope) { 
    $scope.names = [ 
     {"id":1,"value":"NHQ"}, 
     {"id":2,"value":"Chapter"}, 
     {"id":3,"value":"Other"} 
    ]; 

现在我想要在文法上设置下拉选定的项目值。

Still now it is initialized with blank.

我不喜欢的东西:

$scope.selectedName = "Other"; 

但它显然没有奏效。我错过了什么?

P.S. $scope.selectedName can be set to anything . It is just for trial , a simplified version of the problem.

回答

3

使用$scope.selectedName = $scope.names[2];因为names是对象的数组,你需要提供你select with an object设置为默认。

var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    $scope.names = [ 
 
     {"id":1,"value":"NHQ"}, 
 
     {"id":2,"value":"Chapter"}, 
 
     {"id":3,"value":"Other"} 
 
    ]; 
 
    $scope.selectedName = $scope.names[2]; 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl"> 
 

 
<select ng-model="selectedName" ng-options="item.value for item in names track by item.id"> 
 
</select> 
 

 
</div>

1

尝试使用此

<select ng-model="selectedName"> <option ng-selected="selectedName === name.value" ng-repeat="name in names" value="{{name.id}}">{{name.value}}</option> </select>

+1

这会为每个重复例如更好的新范围有'NG-options' HTTPS://docs.angularjs。组织/ API/NG /指令/ ngOptions – Ankanna

相关问题