using angularjs $watch example

How to use AngularJs $watch?

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.
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.$watch('name', function (newValue, oldValue) {
                    $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.$watch('name', function (newValue, oldValue) {
                    $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!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.