设置选择索引

时间:2014-10-21 03:42:28

标签: javascript angularjs ng-options

所以我正在尝试根据某些对象内部的值设置一个select索引。当我遍历对象时,在控制台中我可以看到colorID正在更新和更正,只是选择索引永远不会从上次选择的选项中更改。我错过了什么?提前谢谢。

HTML:

<select 
         ng-model="colorModel" 
         ng-change="updateColor(colorModel.id)" 
         ng-options="i.label for i in colorOptions">
</select>

控制器:

$scope.colorOptions = [
        {value: 'red', label: 'Red', id: 0},
        {value: 'green', label: 'Green', id: 1},
        {value: 'blue', label: 'Blue', id: 2},
        {value: 'yellow',  label: 'Yellow', id: 3}
    ];

//setting it here works just fine
$scope.colorModel = $scope.colorOptions[2];


$scope.nextOption = function(){
      $scope.groupIndex++;
      $scope.currentOption = userOptions[$scope.groupIndex];
      $scope.colorModel = $scope.colorOptions[$scope.currentOption.colorID];
      //I event tried this with no luck
      $scope['colorModel'] = $scope.currentOption.colorID;
}

1 个答案:

答案 0 :(得分:2)

您希望$scope.colorModel中的内容是数组$scope.colorOptions的颜色对象,但您希望在select中显示的内容是label ,对吗?然后,ng-options的正确语法将是:

<select 
         ng-model="colorModel" 
         ng-change="updateColor(colorModel.id)" 
         ng-options="i as i.label for i in colorOptions">
</select>

在控制器中执行以下操作:

app.controller("yourController", function($scope, $filter){
    $scope.colorOptions = [
            {value: 'red', label: 'Red', id: 0},
            {value: 'green', label: 'Green', id: 1},
            {value: 'blue', label: 'Blue', id: 2},
            {value: 'yellow',  label: 'Yellow', id: 3}
        ];

    //setting it here works just fine
    $scope.colorModel = $scope.colorOptions[2];

    $scope.nextOption = function(){
          $scope.groupIndex++;
          $scope.currentOption = userOptions[$scope.groupIndex];
          $scope.colorModel = $filter('filter')($scope.colorOptions, {id:$scope.currentOption.colorID})[0];
    }
});

请注意,您需要在$filter中注入controller服务,如下所示:app.controller("yourController", function($scope, $filter){...

Working Example