Controller not working in Angular JS

I am new to Angular JS. To see the working of controller, I implemented this simple code where two numbers are taken as an input from the users and their sum is calculated in the controller and the result is displayed in the view. But somehow it does not work. The code is as follows :

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>

<body>
<div ng-app="CalculatorApp" ng-controller="CalculatorController">
<p> Number 1 <input type="number" ng-model="a"></p>
<p> Number 2 <input type="number" ng-model="b"></p>
<p> Addition is {{c}} </p>
</div>

angular.module('CalculatorApp', [])
.controller('CalculatorController', function($scope) 
{
$scope.c=$scope.a + $scope.b;
});

</body>
<html>

Please guide.

Hi @Dev747,

The first thing you’ll need to do is wrap your JS in <script> tags, or it won’t get executed by the browser:

  </div>
  <script>
    angular.module('CalculatorApp', [])
      .controller('CalculatorController', function($scope) {
        $scope.c = $scope.a + $scope.b;
      });
  </script>
</body>

Your next problem is that the expression $scope.c = $scope.a + $scope.b; only gets executed once, when the application is initialized and the values of a and b are both undefined.

The simplest way to solve this is simply calculate the result directly in the template:

<p> Addition is {{a+b}} </p>

Ok got the script tags part. But aren’t the values of a and b intialized to user inputs in the constructer as their values are taken as an input from the user in the view. If not, why not? I am totally new to angular js.

Hi, sorry for the late reply.

Basically, when the app starts the controller is executed. At this point, $scope.a and $scope.b don’t exist, so when then line $scope.c = $scope.a + $scope.b; is run $scope.c is set to NaN (which is what you get if you try to add undefined values).

When you enter numbers into the form inputs, Angular puts those values into the $scope.a and $scope.b variables, but $scope.c is still NaN, because the calculation in the controller is never re-executed.

If you need to have code in your controller that reacts to changes in scope variables, you can ‘watch’ them:

$scope.$watch('[a, b]', function(newValue, oldValue) {
  $scope.c = newValue[0] + newValue[1];
});

Here we’re telling Angular “keep an eye on the scope variables a and b, and if either of them change execute this function which will sum the two new values and assign them to c”.

1 Like

OK. But why the calcultion in the controller is never executed even after taking the inputs? Should we use controller for only initializing the data and place the logic part in the functions?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.