在Angular JS中设置选定的下拉选项

时间:2016-07-25 18:28:42

标签: javascript jquery angularjs

我有一个结果列表的下拉列表。

<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.

2 个答案:

答案 0 :(得分: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 :(得分:1)

尝试使用此

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