2014-09-04 108 views
0

嘗試獲取選擇字段中的選項以將數組中的ID用作值。爲選擇使用ng選項生成適當的選項

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打印undefined? 2-爲什麼選項將使用連續值而不是所提供的ID?

+0

在[[fiddle]中可以正常工作(http://jsfiddle.net/2k5msgy8/) – ryeballar 2014-09-04 05:09:11

回答

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