Search code examples
javascriptangularjs2-way-object-databinding

Why is it necessary to create a function in angularjs to return sum of added numbers?


I have been using angularjs in applications for a while, but suddenly i am all lost with this simple illusive nature of angular.

This is my code :

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

First Number: <input type="number" ng-model="firstNumber"><br>
Last Number: <input type="number" ng-model="secondNumber"><br>
<br>
Sum: {{result()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstNumber = 0 ;
    $scope.secondNumber = 0;
    $scope.result = function() {
        return $scope.firstNumber + $scope.secondNumber;
    };
});
</script>

</body>
</html>

Above code is working fine, but the thing i am not getting is, the call to the {{result()}} updates the result in view. That means, the function is triggered each time the values are changed. But with my understanding i wanted following code to work properly but it doesn't.

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.firstNumber = 0 ;
        $scope.secondNumber = 0;
        $scope.result = $scope.firstNumber + $scope.secondNumber;

    });
    </script>

and in view :

Sum : {{result}}

The result shows only the initial result i.e 0 but doesn't show the sum after the input numbers are changed.

Since the result is in scope context and its value should change in each user input change, why does the sum value not being reflected on view.

Please help!


Solution

  • The result in display will change as and when its model is updated in a function that gets continuous updates. Since all the JavaScript statements are executed only once as part of initialization of the controller, the result is evaluated first time and so is the view. But as you change the values, Angular does its job of updating the model for firstNumber and secondNumber with values from input fields and that's it because we didn't tell it to do anything upon change of the value and just like any other programming language feature, neither JavaScript nor Angular will re-compile all JavaScript statements of its controller because it's part of the definition of the controller.

    Next question must be then what happens when we write {{ firstNumber + secondNumber }}, is Angular keeps on evaluating the value for these models and their corresponding view (not the JavaScript statement that is written in controller definition that adds these numbers).