I'm learning AngularJS and JavaScript, and following the examples in the book I'm using, I find something I'd like to understand.
I have a controller that performs one of two mathematical operations, depending on which button is pressed: add and multiply.
var controladorApp = angular.module('controladores', []);
controladorApp.controller('controladorConMetodos', function($scope){
$scope.valor1 = 0;
$scope.valor2 = 0;
$scope.sumar = function () {
$scope.resultado = $scope.valor1 + $scope.valor2;
};
$scope.multiplicar = function() {
$scope.resultado = $scope.valor1 * $scope.valor2;
}
});
On the web page, I simply call each method with its own button and display the result one line after it. The fields input
are the same for both methods.
<div class="" ng-controller="controladorConMetodos">
<input type="text" ng-model='valor1'>
<input type="text" ng-model='valor2'>
<button type="button" name="sumar" ng-click="sumar()">Sumar</button>
<button type="button" name="multiplicar" ng-click='multiplicar()'>Multiplicar</button>
<hr>
<p>{{ resultado }}</p>
</div>
This is my problem: when I use the method multiplicar()
, the result is correct. However, when I call the method sumar()
the values are concatenated and not added .
I guess I have to cast , but I'd like to know why (and how). In the book Warrior's Manual they do n't mention this situation, so I guess it's related to my version of AngularJS, the
1.4.9
, compared to the one1.3.2
used in the book.
you must use
parseInt
Also, you could use
<input type="number">
to prevent non-numeric characters from being entered.Otherwise you should add some type validation.
As for why: This has nothing to do with AngulaJS, it's just javascript. It happens that
*
it does not produce the effect because it does not have a function on itString
, so first it performs the type conversion and then the multiplication. The if operator+
has a function on string, which is concatenate. Therefore there is no conversion.You could also use the element
<input type="number" ... />
This way you don't need to do the conversion in the controller because it's done automatically (well, that's taken care of by Angular
input[number]
's built-in directive )You would also benefit from the rest of the advantages of this element (validation, usability improvements,...)