PortalGuy PortalGuy - 3 months ago 17
AngularJS Question

Angularjs Bind issue

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>

Answer

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()}}
Comments