本文翻译自:How to have a default option in Angular.js select box
I have searched Google and can't find anything on this. 我已经搜索过Google,但找不到任何东西。
I have this code. 我有这个代码。
With some data like this 有了这样的数据
options = [{
name: 'Something Cool',
value: 'something-cool-value'
}, {
name: 'Something Else',
value: 'something-else-value'
}];
And the output is something like this. 输出是这样的。
How is it possible to set the first option in the data as the default value so you would get a result like this. 如何将数据中的第一个选项设置为默认值,这样您将得到这样的结果。
参考:https://stackoom.com/question/1EL9j/如何在Angular-js选择框中使用默认选项
Try this: 尝试这个:
HTML HTML
Javascript 使用Javascript
function Ctrl($scope) {
$scope.options = [
{
name: 'Something Cool',
value: 'something-cool-value'
},
{
name: 'Something Else',
value: 'something-else-value'
}
];
$scope.selectedOption = $scope.options[0];
}
Plunker here . 在这里插一下 。
If you really want to set the value that will be bound to the model, then change the ng-options
attribute to 如果您确实要设置将绑定到模型的值,则将ng-options
属性更改为
ng-options="option.value as option.name for option in options"
and the Javascript to 和Javascript
...
$scope.selectedOption = $scope.options[0].value;
Another Plunker here considering the above. 另一个Plunker 这里考虑以上。
You can simply use ng-init like this 您可以像这样简单地使用ng-init
If you want to make sure your $scope.somethingHere
value doesn't get overwritten when your view initializes, you'll want to coalesce ( somethingHere = somethingHere || options[0].value
) the value in your ng-init like so: 如果要确保在初始化视图时$scope.somethingHere
值不会被覆盖,则需要合并( somethingHere = somethingHere || options[0].value
)ng-init中的值,如下所示:
My solution to this was use html to hardcode my default option. 我的解决方案是使用html硬编码默认选项。 Like so: 像这样:
In HAML: 在HAML中:
%select{'ng-model' => 'province', 'ng-options' => "province as province for province in summary.provinces", 'chosen' => "chosen-select", 'data-placeholder' => "BC & ON"}
%option{:value => "", :selected => "selected"}
BC & ON
In HTML: 在HTML中:
I want my default option to return all values from my api, that's why I have a blank value. 我希望我的默认选项从我的api返回所有值,这就是为什么我有一个空白值。 Also excuse my haml. 还请原谅。 I know this isn't directly an answer to the OP's question, but people find this on Google. 我知道这不是OP的问题的直接答案,但是人们可以在Google上找到它。 Hope this helps someone else. 希望这对其他人有帮助。
I think, after the inclusion of 'track by', you can use it in ng-options to get what you wanted, like the following 我认为,在包含“ track by”之后,您可以在ng-options中使用它来获取所需的内容,如下所示
This way of doing it is better because when you want to replace the list of strings with list of objects you will just change this to 这种方法更好,因为当您要用对象列表替换字符串列表时,只需将其更改为
where somethingHere is an object with the properties name and id, of course. 当然,这里的东西是具有属性名称和ID的对象。 Please note, 'as' is not used in this way of expressing the ng-options, because it will only set the value and you will not be able to change it when you are using track by 请注意,“ as”不会以这种方式表示ng-options,因为它只会设置值,并且在使用track by时将无法更改它