What is $watch
in angular?
Hello
everyone, I am going to share the example for using angular $watch.
The
angular create watch internally. The watch means that angular
watches the changes in the variable on the $scope object. The watches
are created using the $scope.$watch() method and the $scope.watch() method creates a watch of some
variables.
When you register a watch you need to pass two functions
1. One is value function.
2. And other is listener function.
When you register a watch you need to pass two functions
1. One is value function.
2. And other is listener function.
The live demo
example link, go to http://embed.plnkr.co/X1zenc/preview
How to use $watch in angular?
The example
in detail as given below
The Angular
code-sample
var app = angular.module("mywatch", []);
var myController
= app.controller("watchController", function ($scope) {
$scope.name = 'Anil Singh';
$scope.counter = 0;
$scope.counter = $scope.counter + $scope.name.length;
});
});
The HTML
code-sample
<div ng-app="mywatch" ng-controller="watchController">
<input type="text" ng-model="name" />
<label>Counter: {{counter}}</label>
</div>
The Live
demo code-sample (HTML + AngularJs) as given below
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title>AngularJS Using
scope.$watch</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.js"></script>
<script>
var app = angular.module("mywatch", []);
var myController = app.controller("watchController", function ($scope) {
$scope.name = 'Anil Singh';
$scope.counter = 0;
$scope.counter = $scope.counter + $scope.name.length;
});
});
</script>
</head>
<body ng-app="mywatch" ng-controller="watchController">
<input type="text" ng-model="name" />
<label>Counter: {{counter}}</label>
</body>
</html>
The output: go to link http://embed.plnkr.co/X1zenc/preview
Thank you!