[英]AngularJS - disable float filtering
I'm creating a directive in AngularJs. 我正在AngularJs中创建指令。 Directive will receive from app controller a JSON object and based on that the directive will display the content.
指令将从应用程序控制器接收一个JSON对象,并根据该指令显示内容。
I made a simple demo based on my problem that can be found at: http://jsfiddle.net/darkyndy/6StLm/ 我根据自己的问题做了一个简单的演示,可以在以下位置找到: http : //jsfiddle.net/darkyndy/6StLm/
Now my JSON looks something like: ctrlItemJson = { myk: "something", state: { step: 1.0 } };
现在,我的JSON类似于:
ctrlItemJson = { myk: "something", state: { step: 1.0 } };
Why in directive-link, controller and view when I'm accessing state.step
I get 1 instead of 1.0 ? 为什么在访问
state.step
时在指令链接,控制器和视图中获得1而不是1.0 ?
Setting value as string '1.0'
it works, but for me I need to be exactly the same way how it was sent by the controller. 将value设置为字符串
'1.0'
可以正常工作,但是对我来说,我需要使用与控制器发送的方式完全相同的方式。
Later edit: This is mainly from Javascript as if you try var a = 1.0
and then try console.log(a)
you will see 1
以后的编辑:这主要来自Javascript,就像尝试
var a = 1.0
然后尝试console.log(a)
您将看到1
In this case for my issue I will discuss with API guys to send strings... 在这种情况下,针对我的问题,我将与API专家讨论如何发送字符串...
Solution : 解决方案 :
1. In case you cannot control value: 1.如果您无法控制价值:
For where you want to keep decimals (decimals are zeros, eg: 1.0
, 2.00
) instead of using floats then use Strings (eg: '1.0'
, '2.00'
). 对于您想保留小数(小数点后是零,例如:
1.0
, 2.00
),而不是使用花车然后使用字符串(例如: '1.0'
, '2.00'
)。
2. In case you can control and know precision (directive will decide precision): 2.如果您可以控制并知道精度(指令将决定精度):
Then check responses for this question. 然后检查该问题的答案。 Example: http://jsfiddle.net/SE5s3/
示例: http : //jsfiddle.net/SE5s3/
You can specify a certain float precision in JavaScript using .toPrecision(x)
, where x
is the precision you want. 您可以使用
.toPrecision(x)
在JavaScript中指定某个浮点精度,其中x
是所需的精度。
Here's a version of your jsfiddle that implements this: http://jsfiddle.net/SE5s3/ 这是实现此功能的jsfiddle版本: http : //jsfiddle.net/SE5s3/
The specific code I changed: 我更改的具体代码:
<input type="text" value="{{dyItemJson.state.step.toPrecision(2)}}"/>
This is not something AngularJS related, but rather JavaScript. 这与AngularJS无关,而是JavaScript。 For example,
例如,
var a = 2.0;
is actually just 2. 实际上只有2
You can also use the number filter in Angular if you want your numbers to specific decimal places: 如果要将数字指定到特定的小数位,也可以使用Angular中的数字过滤器:
template: '<input type="text" value="{{dyItemJson.state.step | number:2}}"/>',
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.