如何使用angularjs在选择选项字段中设置值

时间:2016-02-01 05:01:00

标签: angularjs

我收到的回复如下,我想调整select option标记中的回复。我该怎么设置那些请建议相同的

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

3 个答案:

答案 0 :(得分:1)

使用ng-repeat和ng-model,如this

<select ng-model='value'>
   <option ng-repeat='option in options'>
     {{option}}
   </option>
</select>

答案 1 :(得分:0)

您可以直接使用数据,而无需使用forEach进行转换。

以下是使用您在评论[{“sport_id”:“1”,“name”:“a”},{“sport_id”:“2”,“name”中提供的数据呈现下拉列表的脚本“:” b “},{” sport_id “:” 3" , “名称”: “C”},{ “sport_id”: “4”, “名称”: “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>

答案 2 :(得分: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>