使用ng-options为select选择生成适当的选项

时间:2014-09-04 04:38:41

标签: angularjs angularjs-scope

尝试获取选择字段中的选项以将数组中的ID用作值。

HTML看起来像这样:

<select class="form-control" name="activitySelector"
       ng-model="item"
       ng-change="changeActivity()"
       ng-options="activity.id as activity.value for activity in activities">
       <option value="">Nothing selected</option>
</select>

控制器:

angular.module('myApp')
    .controller('ActivityCtrl', function ($scope, $rootScope) {
        $scope.activities = [
              {"id":"54be7f8","value":"Add New Activity"},
              {"id":"5407968","value":"Activity 1"}
        ];

        $scope.item = "";

        $scope.changeActivity = function() {
             console.log($scope.item); //prints undefined

        }


    });

生成的HTML如下所示:

 <select ng-options="activity.id as activity.value for activity in activities" ng-change="changeActivity()" ng-model="item" class="form-control ng-pristine ng-valid">
      <option value="" class="">Nothing selected</option>
      <option value="0">Add New Activity</option>
      <option value="1">Activity 1</option>
 </select>

到目前为止我遇到的问题: 1-为什么$ scope.item打印未定义? 2-为什么选项会使用连续值而不是提供的ID?

1 个答案:

答案 0 :(得分:0)

您可以按照以下方式修改代码,以便根据需要呈现html:

<select class="form-control" name="activitySelector"
   ng-model="item"
   ng-change="changeActivity()"
   ng-options="activity.value for activity in activities track by activity.id">
   <option value="">Nothing selected</option>
</select>

现在在你的控制器中,你应该改变如下:

$scope.changeActivity = function() {
    console.log($scope.item.id);
    console.log($scope.item.value); 
 }

以下是Plunker:http://plnkr.co/edit/DWobFzvas9x4lhaoNfTI