如何对 AngularJS 中的两个字段求和并在标签中显示结果? [英] How to sum two fields in AngularJS and show the result in an label?

查看:21
本文介绍了如何对 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.Field1Property.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 中的两个字段求和并在标签中显示结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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