2016-07-25 9 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

これは `NG-options` httpsを持っている方が良い、各繰り返しインスタンスの新しいスコープを作成し、この

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

+1

を使用しよう://docs.angularjsを。 org/api/ng/directive/ngOptions – Ankanna

関連する問題