After utilizing angularjs in various applications for some time, I find myself perplexed by the seemingly straightforward yet elusive nature of Angular.
Here is the code snippet causing my confusion:
<!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>
The above code functions correctly. However, my challenge lies in wanting the following code to operate as expected:
<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 within the view:
Sum : {{result}}
Despite being encapsulated within the scope context, why does the sum value not update in the view upon user input changes?
I seek assistance understanding this scenario!