设置选择索引

Set select index

本文关键字:索引 选择 设置      更新时间:2023-09-26

所以我试图根据一些对象内部的值设置一个选择索引。当我循环浏览对象时,在控制台中,我可以看到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;
}

您似乎希望在$scope.colorModel中显示的是Array $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];
    }
});

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

工作示例