Search code examples
javascriptangularjsng-optionsangular-ngmodel

Select default value at ng-options


I have this code and information:

$scope.options = [
  { id: 1, label: "My label" },
  { id: 2, label: "My label 2" }
];
$scope.selected = 2;

<select ng-options="opt.label for opt in options" ng-model="selected">
  <option value="">Select one</option>
</select>

However, the options are created like this:

<select ng-options="opt.label for opt in options" ng-model="selected">
  <option value="">Select one</option>
  <option value="0">My label</option>
  <option value="1">My label 2</option>
</select>

How can I set the selected option to My label 2? I know it can be done:

$scope.selected = $scope.options[1];

But my problem is that option is created in a directive, and at that moment I don't know 1) how many values has $scope.options, nor 2) what is the index of the selected option in database. The only thing I know is the id (which is in the object).

The html of my directive is something like this:

<select ng-switch-when="select" ng-model="form.model[element.model]" ng-options="{{element.rule}}"></select>

Where element.rule is:

rule: "role.role for role in element.options"

And element.options has the array with options, and form.model[element.model] has the id of the option selected.

How can I get the index of the element with ID X in the array $scope.options? I'm very sure that will give me the solution, but I don't know how to do it...


Solution

  • Just set the correct model value when initiating the controller. You can easily get the correct array value if you know the ID by using a filter:

    $scope.selected = $filter('filter')($scope.options, {id: 2})[0];