Use of watch in AngularJS

Posted By : Dipak Kumar Singh | 22-Jun-2016

There are many other ways to communicate with different controllers but “$watch” is simple way .“$watch” concept in Angular is to observe the changes on the data of the scope from the controller.you have to communicate with two different controllers you can use $watch concept. we understand by this example:-

Suppose we have a function in Controller A

Controller A

angular.module('sampleproject').controller( 'ControllerA',
function ($rootScope, $scope ,samplefactoryService )
{
 $scope.sampleView = function( status )
 { 
  $rootScope.sampleStatus = status ;
 };
});
 

 

Status is changing on each click of this function sampleView ( ng-click = “sampleView();”) and we have to execute a function in controller 2 
(That is on change of this $ rootScope variable )

Note:-$rootScope is global, we can access anywhere in the same module

Controller B

angular.module('sampleproject').controller( 'ControllerB',
function ($rootScope, $scope ,anotherService )
{
 
$rootScope.$watch('sampletStatus', function( status )
  {
 if( status )  // onchange of status in controller B
 {
  if( status == 'your')
  {
   //your logic
  }
  // else if .....
 }
  }
});
 

Here Watch will work as a internal trigger .It will identify the changes of status variable in controller A and will update the controller B. 

THANKS

About Author

Author Image
Dipak Kumar Singh

Dipak is a skilled HTML Developer, expertise in UI Development. Dipak likes watching movies and playing computer games.

Request for Proposal

Name is required

Comment is required

Sending message..