如何使用AngularJS在选择字段中将预选选项设置为默认选项 [英] How to set a preselected option as default in a select field using AngularJS

查看:69
本文介绍了如何使用AngularJS在选择字段中将预选选项设置为默认选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用AngularJS在HTML中设置选择框的默认值时遇到了麻烦。

I am having troubles with setting the default value of a select box in HTML using AngularJS.

这是我在控制器中的范围变量:

Here's my scope variable in the controller:

$scope.sensorReadingsPerPage = 30;

这里是使用控制器的视图中的选择框:

and here's the selection box in the view that's using the controller:

<select id="itemsPerPage" name="itemsPerPage" class="panel panel-default" ng-model="sensorReadingsPerPage" ng-change="changeItemsPerPage()">
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="30">30</option>
  <option value="40">40</option>
  <option value="50">50</option>
  <option value="100">100</option>
</select>

我希望预先选择30值的选项。

I want the option with '30' value to be preselected.

我尝试过使用这个答案和这个一个,两个都引用了关于select指令的AngularJS文档,但在这些情况下,选项是以动态方式生成的,范围包含一个包含多个值的对象。在我的情况下,选项是静态的,并且范围上只有一个变量。

I've tried using this answer and this one, both of them referencing AngularJS documentation on select directive, but in these cases the options are being dinamically generated AND the scope consists in an object with several values in it. In my case, the options are static and there's just a variable on the scope.

我该如何解决这个问题?有没有办法更改 ng-init ng-options 以适合我的情况?

How can I go around this? Is there a way to change the ng-init and ng-options to fit my case?

推荐答案

尝试在控制器中设置 $ scope.sensorReadingsPerPage =30

注意:它应该是一个字符串。

Note: It should be a string.

这篇关于如何使用AngularJS在选择字段中将预选选项设置为默认选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆