Select default value at ng-options

不打扰是莪最后的温柔 提交于 2019-12-23 05:29:26

问题


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...


回答1:


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



回答2:


The issue with your code as I see it is that the 'selected' value coming out of your database is the ID of the object selected and not the object itself. This is fine but because of that difference you can't simply set

$scope.selected = 2 //assuming 2 is the value coming from your database

because the value '2' does not exist in your option array. The Object with an ID of 2 does.

If you can always guarantee the options you have in the option array are from 1-n and in that order, you can accomplish this by simply using this instead:

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

If you can't make that guarantee (and even if you can for now, it may not be a good idea to make that assumption in your code) you'll need iterate over the array of objects you have to identify the object with an ID of the selectedId from your database.

The answer to this question has a great write-up about the type of data-processing you'll need to do and a lot more information about javascript objects in general.



来源:https://stackoverflow.com/questions/25222309/select-default-value-at-ng-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!