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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book