Simple Calculator with ng-click
A basic four-function calculator built in AngularJS that demonstrates real-time two-way binding and event handling with ng-click
.
Why this works
AngularJS binds the calculator screen to the display
model. Each
button emits a value through ng-click
; the controller concatenates
or evaluates the expression with $eval
. No manual DOM updates are
needed—AngularJS updates the view automatically.
Source Code
<!-- Calculator HTML -->
<div ng-app="calcApp" ng-controller="CalcCtrl">
<input type="text" ng-model="display" readonly>
<div ng-repeat="btn in buttons">
<button ng-click="press(btn)">{{btn}}</button>
</div>
<button ng-click="clear()">C</button>
</div>
<!-- AngularJS logic -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
angular.module('calcApp',[])
.controller('CalcCtrl',function($scope){
$scope.display='';
$scope.buttons=['7','8','9','/','4','5','6','*','1','2','3','-','0','.','=','+'];
$scope.press=function(val){
if(val==='='){ $scope.display=$scope.$eval($scope.display); }
else { $scope.display+=val; }
};
$scope.clear=function(){ $scope.display=''; };
});
</script>