0

Hi All I have checked for solutions online for my problem but nothing resolved my problem.

HTML5 code :

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body ng-app="myApp">
        <div id="div1" ng-controller = "myCont">
        <input id="txt1" type="text" ng-model="a" ng-change="updateC()">
        <input id="txt2" type="text" ng-model="b">
        <div>a {{a}}</div>
        <div>s {{s}}</div>
        <div>c {{c}}</div>
        <script src="angular.js"></script>
        <script src="angular_try.js"></script>
    </body>
</html>

Below is my angularjs code :

var myApp= angular.module("myApp",[])

myApp.controller("myCont",["$scope","$rootScope",function($scope,$rootScope)
{
     $scope.s=0;
     $scope.a =0;
     $scope.b=0;
     function updateC()
     {
         $scope.c = $scope.a+20;
     }


     $scope.$watch("c",function(newvalue,oldvalue){
        if(newvalue!=oldvalue)
        {
             $scope.c =$scope.c
        }
   })
}])

Could anyone please let me know what is wrong in my code as I am using ng-change with ng-model and also have watch expression for the same but code doesn;t run , tough there is no error.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
titlu
  • 119
  • 2
  • 9

2 Answers2

1

Just do

$scope.updateC = function ({
  $scope.c = $scope.a+20;
}
0

Attach the function to your scope:

 $scope.updateC = function() {
     $scope.c = $scope.a+20;
 }

Also, to avoid issues with prototypal inheritance, you may want to create an object and bind to properties of that object, instead of binding directly to the scope:

Controller:

$scope.data = {
    a: 0, 
    // etc
}

View:

ng-model="data.a"

Or you can switch to the controller as syntax. Check out this link for details.

Frank Modica
  • 10,238
  • 3
  • 23
  • 39