Reputation: 35
I have a simple sample code , consists of 3 variables a b and testvar, testvar is sum of a and b, I am trying to understand why the binding does not work for variable testvar when value of a changes , I have created a input with its model as a. How this can be achieved, Any help is greatly appreciated
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input ng-model="mymodel.a"><br>
Why this value does ot change on changing input:{{ mymodel.testvar}}
<br>
mymodel.a changes on input change: {{mymodel.a}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.mymodel={};
$scope.mymodel.a=1;
$scope.mymodel.b=2
$scope.mymodel.testvar =$scope.mymodel.a+$scope.mymodel.b;
});
</script>
<p>Test Binding.</p>
</body>
</html>
Upvotes: 1
Views: 36
Reputation: 1861
The reason your mymodel.testvar
does not get updates when you change mymodel.a
or mymodel.b
is because when your controller is run for the first time testvar
is evaluated to the sum of a
and b
's initial values hence testvar
is equal to 3. So the variable testvar
stores the literal value 3. Now when you change a
or b
to let's say 4 you are not re-evaluating testvar
. testvar
is still 3. In scenarios like this if you want to recalculate testvar
to have to put it into a function like mymodel.testvar = function(){ return mymodel.a + mymodel.b};
you then bind to the function call. Or in angular you can bind to the addition expression directly something like {{mymodel.a + mymodel.b}}
Upvotes: 1
Reputation: 4561
This line:
$scope.mymodel.testvar =$scope.mymodel.a+$scope.mymodel.b;
Binds a + b
to testvar
only one time, using the initial values of a
and b
.
One solution is to turn testvar
into a function, like this:
// Javascript
$scope.getTestVar = function() {
return $scope.mymodel.a+$scope.mymodel.b;
};
<!-- HTML -->
TestVar: {{getTestVar()}}
Upvotes: 1