Watch is a powerful feature of angular js. “$watch” concept in Angular is to observe the changes on the data of the scope from the controller. That is controller can add a listener on an attribute of its scope. Suppose you have to communicate with two different controllers you can use $watch concept. We can explain this with a working example.
Suppose we have a function in Controller 1
Controller 1
 
angular.module('sampleproject').controller( 'Controller1',
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 but $scope can access only in a particular controller.
Controller 2
 
angular.module('sampleproject').controller( 'Controller2',
function ($rootScope, $scope ,anotherService )
{
 
$rootScope.$watch('sampletStatus', function( status )
  {
 if( status )  // onchange of status in controller 1
 {
  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 1 and will update the controller 2.
There are many other ways to communicate with different controllers. This is one simple example using $watch concept
Related Posts
1. Communicate with controllers in angular js
3. Rating Stars using angular js Directive concept
5. Filtering concept in angular js
 

 
This is only a one method , can use in several ways .
ReplyDeleteNice Tutorials thanks
ReplyDeleteSorry but you have typos in your code and the example was tricky to get working properly. A little Plunk or Fiddle is always nice.
ReplyDeleteVery nice, thank you for such a simple example. Something I struggle with many days to understand, work in a charm after reading this one.
ReplyDeletei can not execute this code, can u please post full code.
ReplyDelete