view raw
PortalGuy PortalGuy - 9 months ago 76
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>
<script src=""></script>

<div ng-app="myApp" ng-controller="myCtrl">

<input ng-model="mymodel.a"><br>
Why this value does ot change on changing input:{{ mymodel.testvar}}
mymodel.a changes on input change: {{mymodel.a}}

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

$scope.mymodel.testvar =$scope.mymodel.a+$scope.mymodel.b;

<p>Test Binding.</p>



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