What is $watch
in angular?
Angular $watch is used to watching the valuable changes of scope objects.
Why use angular
$watch?
The angular $watch is create internally. If you want to create custom
watch then you need to use $scope.$watch and also need to pass the two
parameters one is value function and other is listener function i.e.
$scope.$watch('watch', function (function(){},function(){}) {});
Watch parameter types,
1.
Value function
2.
Listener function
Syntax:
$scope.$watch('watching', function (valueFun, listenerFun) {});
//AngularJs code-sample var app = angular.module("watchApp", []); app.controller("watchCtrl", ["$scope", function ($scope) { $scope.count = 0; $scope.watching = 'Anil kr. Singh'; //THIS IS USED FOR WATCHING TO "WATCHING" IN SCOPE AND RETURN THE LENGTH OF IT. $scope.$watch('watching', function (n1, o1) { $scope.count = $scope.count + $scope.watching.length; }); }]);
//Live demo example(HTML + AngularJs) code-sample <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>$watch in AngularJs</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script> <script> var app = angular.module("watchApp", []); app.controller("watchCtrl", ["$scope", function ($scope) { $scope.count = 0; $scope.watching = 'Anil kr. Singh'; //THIS IS USED FOR WATCHING TO "WATCHING" IN SCOPE AND RETURN THE LENGTH. $scope.$watch('watching', function (n1, o1) { $scope.count = $scope.count + $scope.watching.length; }); }]); </script> </head> <body ng-app="watchApp" ng-controller="watchCtrl"> <h1>$watch in AngularJs</h1> <div> <input type="text" ng-model="watching" /> <label>Count Result : {{count}}</label> </div> </body> </html>The Live Output,
Blogger Comment
Facebook Comment