Just started learning AngularJS. I was trying to understand the two-way data binding by writing a code that adds two numbers from the input boxes. Here's what I have written:
HTML
<div ng-app="cal">
<div ng-controller="calc">
<input type="text" ng-model="a"/>
<input type="text" ng-model="b"/>
<span>{{result}}</span>
</div>
</div>
JavaScript
var app=angular.module("cal", []);
app.controller("calc",function ($scope) {
$scope.result=Number($scope.a || 0)+ Number($scope.b || 0);
});
This, however, doesn't give the intended result i.e "result" is not updated automatically.
But the following code works:
HTML
<div ng-app="cal">
<div ng-controller="calc">
<input type="text" ng-model="a" ng-keyup="add()"/>
<input type="text" ng-model="b" ng-keyup="add()"/>
<span>{{result}}</span>
</div>
</div>
JavaScript
app.controller("calc",function ($scope) {
$scope.add=function(){
$scope.result=Number($scope.a || 0)+ Number($scope.b || 0);
}
});
Why do I need the "keyup" directive? Shouldn't the variable "result" be updated automatically as the values in the fields change?
I also created a jsfiddle here: https://jsfiddle.net/Deadboy/m9ket0sL/