Search code examples
javascriptangularjsng-options

Set select index


So I'm trying set a select index based on a value inside of some objects. As I cycle through the objects, in console I can see that the colorID is being updated and correct, just that the select index never changes from the option that was last selected. What am I missing? Thanks in advance.

HTML:

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

Controller:

$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;
}

Solution

  • It seems that what you want to have in $scope.colorModel is the color object of the Array $scope.colorOptions, but what you want to display in the select is the label, correct? Then, the correct syntax for ng-options would be:

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

    In the controller do this:

    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];
        }
    });
    

    Notice that you will need to inject the $filter service in your controller, like this: app.controller("yourController", function($scope, $filter){...

    Working Example