I'm beginner on AngularJs and I have a difficult to show the sum of two numbers. The first script work perfectly :
<div>
<p><input type="text" ng-model="price1" /> <strong>{{price1}}</strong></p>
<p><input type="text" ng-model="price2" /> <strong>{{price2}}</strong></p>
<p><strong>{{total = (price1 * 1 + price2 * 1) }}</strong></p>
</div>
But when I try to test this using a controller, like this :
<div ng-controller="myCtrl">
<p><input type="text" ng-model="price1" /> <strong>{{price1}}</strong></p>
<p><input type="text" ng-model="price2" /> <strong>{{price2}}</strong></p>
<p><strong>{{total}}</strong></p>
</div>
<script>
var app = angular.module('firstApp', []);
app.controller('myCtrl', ['$scope', function($scope) {
$scope.total = ($scope.price1 + $scope.price2);
}]);
</script>
I have no result, just a NaN value. I have no idea what happen !
There are several issues in your code:
$scope.price1 and $scope.price2 are not defined
once the controller is initialized. Arithmetical operation using
undefined value produces NaN as the result.$scope.total just once. Its result is not updated on change of
$scope.price1 or $scope.price2type="number" not type="text" then the values of $scope.price1 and $scope.price2 will be parsed and summed up as numbers. In your code they are concatenated as strings.var app = angular.module('myApp', []);
app.controller("myCtrl", function ($scope) {
$scope.price1 = 1;
$scope.price2 = 2;
$scope.getTotal = function() {
return $scope.price1 + $scope.price2;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<p><input type="number" ng-model="price1" /> <strong>{{price1}}</strong></p>
<p><input type="number" ng-model="price2" /> <strong>{{price2}}</strong></p>
<p><strong>{{getTotal()}}</strong></p>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With