Skip to content

Instantly share code, notes, and snippets.

@soiqualang
Created November 12, 2019 04:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soiqualang/b34114ff1cc927f15bccfea2afd08b6b to your computer and use it in GitHub Desktop.
Save soiqualang/b34114ff1cc927f15bccfea2afd08b6b to your computer and use it in GitHub Desktop.
How to $watch multiple variable change in AngularJs
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>var1: <input type="text" ng-model="var1"></p>
<p>var2: <input type="text" ng-model="var2"></p>
<p>var3: <input type="text" ng-model="var3"></p>
<p>{{kq}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.var1=1;
$scope.var2=3;
$scope.var3=0;
$scope.arr1=[$scope.var1,$scope.var2,$scope.var3];
$scope.kq=$scope.arr1.reduce((a, b) => a + b, 0);
$scope.$watch('[var1,var2,var3]', function (newValue,oldValue) {
$scope.arr1=[newValue[0],newValue[1],newValue[2]];
$scope.kq=$scope.arr1.reduce((a, b) => a*1 + b*1, 0);
});
});
//https://stackoverflow.com/questions/16729965/how-to-watch-multiple-variable-change-in-angular
</script>
</body>
</html>
@soiqualang
Copy link
Author

soiqualang commented Nov 12, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment