How to sum two fields in AngularJS and show the result in an label?(如何对 AngularJS 中的两个字段求和并在标签中显示结果?)
问题描述
我的页面上有一个情况.
I have an situation on my page.
我的页面中有两个输入和一个标签.这些标签必须显示这两个输入值的总和.
I have two inputs and an label in my page. These label have to show the sum of these two inputs value.
所以我尝试了以下解决方案:
So I tried below solution:
Sub-Total
<input type="text" ng-model="Property.Field1" />
Tax
<input type="text" ng-model="Property.Field2" />
Total
<label>{{ Property.Field1 + Property.Field2 }}</label>
第一次,当页面完全加载时,标签显示总和但是当我在任何输入中键入一些值时,这些解决方案给了我 Property.Field1
和 Property.Field2
的 CONCATENATION 结果,而不是总和.
At the first time, when the page is totaly loaded, the label shows the sum but when I type some value in any input,
these soution gives me a CONCATENATION result of Property.Field1
and Property.Field2
, instead of the sum.
所以我尝试了这些:
Sub-Total
<input type="text" ng-model="Property.Field1" />
Tax
<input type="text" ng-model="Property.Field2" />
Total
<label>{{ parseFloat(Property.Field1) + parseFloat(Property.Field2) }}</label>
再次没有成功.
如何实现标签中显示的两个输入的总和结果?
How could I achieve the sum result of two inputs shown in the label?
推荐答案
你真的在你的控制器中创建了一个 parseFloat
方法吗?因为您不能简单地在 Angular 表达式中使用 JS,请参阅 Angular 表达式与 JS 表达式.
Have you actually created a parseFloat
method in your controller? Because you can't simply use JS in Angular expressions, see Angular Expressions vs. JS Expressions.
function controller($scope)
{
$scope.parseFloat = function(value)
{
return parseFloat(value);
}
}
也应该可以简单地设置对原始函数的引用:
edit: it should also be possible to simply set a reference to the original function:
$scope.parseFloat = parseFloat;
我也希望它可以与过滤器一起使用,但不幸的是它不是(可能是一个错误,或者我误解了过滤器的工作原理):
I would also expect it to work with filters, but unfortunately it doesn't (might be a bug, or i've misunderstood how filters work):
<label>{{ (Property.Field1|number) + (Property.Field2|number) }}</label>
一种解决方法是使用乘法进行转换:
A workaround would be to use multiplication for casting:
<label>{{ (Property.Field1 * 1) + (Property.Field2 * 1) }}</label>
这篇关于如何对 AngularJS 中的两个字段求和并在标签中显示结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何对 AngularJS 中的两个字段求和并在标签中显示


基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01