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!