2016-02-01 142 views
2

我收到如下響應,我想調整select option標記中的值。如何設置這些請建議相同如何使用angularjs在選擇選項字段中設置值

[null,"a","b","c ","d"] 

我的代碼是這樣

$http.get('v1/sport').success(function(data) { 
    $scope.sports = []; 
    //$scope.sports = data.data; 
    angular.forEach(data.data, function(value, key) { 
     $scope.sports[value.sport_id] = value.name; 
    }); 
}); 

鑑於

<select name="teamSport" 
         ng-model="player.sport_id" 
         ng-options="sport[player.sport_id] as sport[player.name] for sport in sports" 
         ng-change="changedSport()" 
         required> 
         <option value="" selected="selected">-- Select --</option> 
        </select> 

+0

這裏角度選擇文檔HTTP s://docs.angularjs.org/api/ng/directive/select – MasoodUrRehman

+0

請分享您的HTML文件?也分享$ scope.sports數據 –

+0

您有沒有查看 {「sport_id」:「1」,「name」:「 「sport_id」:「2」,「name」:「b」},{「sport_id」:「3」,「name」:「c」},{「sport_id」:「4」,「名稱「:」d「}] || {「sport_id」:「3」,「name」:「c」} 打電話給我,我得到 {{sports}} || {[sports.sport_id]}} – Priya

回答

0

您可以直接使用數據,而不及如何使用foreach將其轉換。

下面是使用您在評論[{「sport_id」:「1」,「name」:「a」},{「sport_id」:「2」,「名稱「:」b「},{」sport_id「:」3「,」name「:」c「},{」sport_id「:」4「,」name「:」d「}]

您可以在$ scope.selected變量中設置所選內容。

var myApp = angular.module('myApp', []) 
 

 
.controller('MyController', ['$scope', function($scope) { 
 
    
 
     $scope.sports = [{"sport_id":"1","name":"a"},{"sport_id":"2","name":"b"},{"sport_id":"3","name":"‌​c"},{"sport_id":"4","name":"d"}]; 
 
    
 
    $scope.selected = $scope.sports[2]; 
 
    
 
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="myApp"> 
 
    
 
<div ng-controller="MyController"> 
 
{{selected}} 
 
<select name="teamSport" 
 
         ng-model="selected" 
 
         ng-options="sport as sport.name for sport in sports" 
 
         ng-change="changedSport()" 
 
         required> 
 
         <option value="" selected="selected">-- Select --</option> 
 
        </select> 
 
    </div> 
 
    </div>

1

使用NG重複和NG-模型像this

<select ng-model='value'> 
    <option ng-repeat='option in options'> 
    {{option}} 
    </option> 
</select> 
0
$http.get('v1/sport') .success(function (data) { $scope.sports = []; angular.forEach(data.data, function(value, key){ $scope.sports[value.sport_id] = value.name; }); }); 
$http.get('v1/selectedSport') .success(function (data) { $scope.selectedSport = data; }); 

和視圖

<select 
     ng-model="selectedSport" 
     ng-options="sport[player.sport_id] as sport[player.name] for sport in sports"> 
</select> 
+0

給出的數據[null,「a」,「b」,「c」,「d」]沒有sport_id和名字 – Siva

+0

@Siva不知道這是個問題,但是接下來這個問題還不清楚......> _ <我把這個問題看作設置selectedItem – Aron

相關問題