Sunday, 2 March 2014

How to use watch concept in Angular js

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

2. Angular routing

3. Rating Stars using angular js Directive concept

4. Loop concept in angular js

5. Filtering concept in angular js


4 comments :

  1. This is only a one method , can use in several ways .

    ReplyDelete
  2. Nice Tutorials thanks

    ReplyDelete
  3. Sorry but you have typos in your code and the example was tricky to get working properly. A little Plunk or Fiddle is always nice.

    ReplyDelete
  4. Very nice, thank you for such a simple example. Something I struggle with many days to understand, work in a charm after reading this one.

    ReplyDelete