Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - How to sum two fields in AngularJS and show the result in an label?

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>

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.

so I tried these:

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>

no sucessful again.

How could I achieve the sum result of two inputs shown in the label?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...