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 中的两个字段求和并在标签中显示


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06