PortalGuy PortalGuy - 1 year ago 111
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="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></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>


Answer Source

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()}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download