如何在 AngularJS 中对两个字段求和并将结果显示在标签中?

编程入门 行业动态 更新时间:2024-10-28 10:26:13
本文介绍了如何在 AngularJS 中对两个字段求和并将结果显示在标签中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我的页面上有一个情况.

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>

第一次,当页面完全加载时,标签显示总和但是当我在任何输入中输入一些值时,这些 soution 给了我 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 04:47:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1015676.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并将   字段   中对   两个   标签

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!