How to select the option in ngOptions with the help of the third parameter present in the option object?

62 Views Asked by At

I have options array for select dropdown like

[
    {key:1,value'foo',selected:true},
    {key:2,value'foo2',selected:false}
]

I want to select option value with the property selected true in my model. So for this option array of my model should be initialized and bind to 1.

Any help is appreciated!! Thanks in advance :)

For this i know i can do it by looping in controller and setting the value whose property selected is true. I am looking for an alternative which is better. Also i have tried ng-repeat on options and it works, but i think ngOptions is better from the view of performance.

1

There are 1 best solutions below

0
eustatos On

If I understood the requirements correctly:

angular.module('selectExample', [])
  .controller('ExampleController', ExampleController);

ExampleController.$inject = ['$scope'];

function ExampleController($scope) {
  $scope.selectOptions = [{
      key: 1,
      value: 'foo',
      selected: true
    },
    {
      key: 2,
      value: 'foo2',
      selected: false
    }
  ];
  
  $scope.filterOptions = filterOptions;
  
  setFirstOptions($scope, 'selected', $scope.selectOptions);
}

function filterOptions(data) {
  return data.filter(function(item) {
    return item.selected;
  });
}

function setFirstOptions($scope, variable, data) {
  var filteredOptions = filterOptions(data);
  if (filteredOptions.length > 0) {
    $scope[variable] = filteredOptions[0];
  }
}

angular.bootstrap(
  document.querySelector('body'), ['selectExample']
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-controller="ExampleController">
  <select ng-model="selected" ng-options="option.value for option in filterOptions(selectOptions)">
</div>