thawts
thawts

Reputation: 81

angular 1.x ng-options load dropdown from value

https://plnkr.co/edit/lvxHUKXI9tuToSNsD3Hg?p=preview

Here is my plunker, I have my html like this

<select ng-model="dropdown" ng-options="option.description for option in list" ng-change="hmm()"></select>

Then my datasource looks like this

$scope.list =   {"description":"jhello","value":4},"description":"bello","value":5}];
$scope.dropdown = 5;

I have a ng-model="dropdown"

What I want to do is have the value of the model set to the selected option. So if I set dropdown=5, then the $scope.list[1] would be selected. I know I can easily just call the index so $scope.dropdown = $scope.list[1] etc. However this requires extra mapping when I pull data out of the database for editing to map to this option. Then extra mapping to only store the 5 value into the database when I am trying to save (IE valueToSave = $scope.dropdown.value). It would be nice if my model or value could automatically set up the correct option and automatically be ready for saving. When you have 30 or so dropdowns and someone clicks edit the extra mapping to set the dropdowns and save again is really adding up. How can I set the dropdown option using $scope.dropdown = 5 and also make sure changes to the drop down update $scope.dropdown to the correct value so it is ready to save?

Upvotes: 2

Views: 91

Answers (2)

Theraloss
Theraloss

Reputation: 700

I think mapping is the best way.

With this function, you can easily find and assign the correct value.

function findIndexInData(data, property, value) {
  var result = -1;
  data.some(function (item, i) {
    if (item[property] === value) {
      result = i;
      return true;
    }
  });
  return result;
}

So you can use this:

$scope.list[ findIndexInData( $scope.list, 'value', 5 ) ];

See the plunker

Upvotes: 0

user1846747
user1846747

Reputation:

Just update your ng-options as follows ng-options="option.value as option.description for option in list"

Like this

<select class="dropdown-list form-control" name="UnitsOfLengthDefault" ng-model="dropdown" ng-options="option.value as option.description for option in list" ng-change="hmm()"></select>

Upvotes: 1

Related Questions