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 :
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:
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.
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:
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â.
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?