简体   繁体   English

AngularJS使用HTML选择标签选择整数值

[英]AngularJS select integer value with HTML select tag

I'm new to AngularJS. 我是AngularJS的新手。 I have a very simple task: select an integer value with angular using an HTML <select> tag. 我有一个非常简单的任务:使用HTML <select>标记选择一个带角度的整数值。

<select ng-model="foo.bar">
    <option ng-repeat="option in options" value="{{option}}">{{option}}</option>
</select>

foo.bar holds an integer value. foo.bar保存一个整数值。 When I run the above code, the first generated option is: <option value="? number:32 ?"></option> . 当我运行上述代码时,第一个生成的选项是: <option value="? number:32 ?"></option> I have found out that the selected value is interpreted as a String. 我发现所选的值被解释为字符串。 I want an Integer. 我想要一个整数。

I have found some possible solutions, but they are either complex (like the documentation example to implement a convert-to-number -function ) , or their options array looks different (mine is just a simple array of integers). 我已经找到了一些可能的解决方案,但是它们要么很复杂( 例如用于实现convert-to-number -function文档示例 ),要么它们的options数组看起来有所不同(mine只是一个简单的整数数组)。

Instead of the option tag combined with ng-repeat you should use angulars ng-options directive like this: 与其将option标签与ng-repeat结合使用,不如使用angulars ng-options指令,例如:

<select ng-model="foo.bar" ng-options="option for option in options"></select>

If options is an array of integers, ng-model should contain an integer as well. 如果options是一个整数数组,则ng-model应包含一个整数。

Select will give you a string. 选择将给您一个字符串。 You will have to convert that string into a number in your controller code. 您将必须在控制器代码中将该字符串转换为数字。

foo.bar = parseInt(foo.bar);

You may need to use a watch to look for changes in your foo.bar variable and then parse them to integer. 您可能需要使用监视程序来查找foo.bar变量中的更改,然后将其解析为整数。

Take a look at https://docs.angularjs.org/api/ng/type/ $rootScope.Scope and search for $watch. 看一下https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope并搜索$ watch。

Select dropdown will give you string value always, if you want it to be an integer covert it in controller 选择下拉列表将始终为您提供字符串值,如果您希望它成为控制器中的整数隐藏值

Controller - 控制器 -

var numValue = Number(foo.bar);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM