How to sum two fields in AngularJS and show the result in an label?
The Columbus's egg is: double negation.
The initial value will be 0 (instead of null), and the result will be a sum (instead of a concatenation, because of the implicit numeric cast).
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app>
<input ng-model="first" placeholder="First number" type="text" />
<input ng-model="second" placeholder="Second number" type="text" />
<h1> Sum: {{first--second}}! </h1>
</div>
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>
The easiest and best way to sum two numbers is using HTML5's type="number"
. If you do this, the inputs' values are, by default, integers.
Updated fiddle