Friday 21 March 2014

Communicate with controllers in angular js

There are many ways to communicate with different controllers .Some of them are

1. Share data between controllers by making function as Global
2. Share data between controllers using factory file
3. Using $emit or $broadcast
4. Using Watch Concept.

1. Share data between controllers by making function as Global


We have one ng-click function in controller1 .Onclick of this we have to share a data to controller 2 and invoke another function.

Controller 1

 
 
angular.module('sampleproject').controller( 'Controller1',
function ($rootScope, $scope )
{
  $scope.shareData = function( data ){
  
  $scope.sampleFunction( data) ;
   
  };
}); 
 

Controller 2

 
 
angular.module('sampleproject').controller( 'Controller2',
function ($rootScope, $scope )
{
  $rootScope.sampleFunction = function( data ){
  
  console.log(data);
  // your logic
   
  };
}); 
 

Here we are making function as global using $rootScop .We can access this function anywhere in the module.

2. Share data between controllers using factory file .


The most common and recommended method for sharing data between controllers is to use a service. Make a factory file common for controllers .

View



<div ng-app="sampleApp">
    
 <div ng-controller="Ctrl1">Controller 1: {{foo}}</div>
    
 <div ng-controller="Ctrl2">Controller 2: {{foo}}</div>

</div>


Factory File



var app = angular.module('sampleApp', []);

app.factory('Service', function() {
 
 var Service = {
    foo: 'Shared service'
  };
 
 return Service;
});



Controller 1




app.controller('Ctrl1', function($scope, Service) {

  $scope.foo = Service.foo;

  Service.foo = 'I am from contoller 1';

  });


Here Service is the factory file name.

Controller 2



app.controller('Ctrl2', function($scope, Service) {
  
  $scope.foo = Service.foo;

});


Play in fiddle

3. Using $emit or $broadcast


You can communicate between controllers using $emit and $broadcast as well, check below example for that.


$scope.$emit('itemClicked', [_item]);
$rootScope.$on('itemClicked',function (e, args, status)
{
 //your actions  
});


$rootScope.$broadcast('$newItemsClicked');
$rootScope.$on('$newItemsClicked', function() {
 //your actions
});

4. Using Watch Concept.


Third method is using watch concept .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.
Using Watch Concept

Related Posts

1. Angular flash message using directive

2. Angular routing

3. Rating Stars using angular js Directive concept

4. Communication between factory file and controller in Angular js


19 comments :

  1. Great one .....

    ReplyDelete
  2. useful one!!!!

    ReplyDelete
  3. i was searching for this , thanks

    ReplyDelete
  4. Really helpfull ..thanks a lot

    ReplyDelete
  5. thanks but I don't understand why in the second example, with Factory, only the second Controller is updated with the new foo value ?

    the first stay in initial value : "Shared service"

    ReplyDelete
    Replies
    1. Because "shared service " is common for both controllers . I just given an example of how to share data between different controllers . Here controller two is taking the data from controller one and controller one is taking the shared service data . You can make this in either way .

      Delete
    2. I still don't understand? the 'shared service' date should be gone after updating foo?

      Delete
    3. If you call the service from the controller 1 again then you will see the updated value.
      As for the first time you don't see updated value because it was already printed before updation.

      Delete
  6. Nice explanation!! easy to understandable !!!

    Thank you!!!

    ReplyDelete
  7. PubSub pattern would be better?

    ReplyDelete
  8. It is really helpful and easy to understandable!!!

    ReplyDelete
  9. Hi,
    I have two different controller files and two different HTML files like controller1,HTML file1 and controller2,HTML file2.Im using the 2nd approach from Here--Share data between controllers using factory file:-
    I used your example- 'Service' in both controller files--->.factory('Service',function()
    {
    var Service={
    foo:"shared service"
    };

    return Service;
    });
    My controller 1 consists--> $scope.foo=Service.foo;
    Service.foo='I am from controller1';
    My controller2 consists of --> $scope.foo = Service.foo;
    In my both HTML Files -i kept this -->
    tags-div {{foo}} /div. The problem is when running im not getting the message - 'I am from contoller 1'.Instead im getting the message from Service:-foo: 'Shared service'.
    If i remove the 'Service' in 2nd controller,it is showing the error like unknown provider.Can you provide a solution for this.

    ReplyDelete
  10. Good, Thanks a lot, but which is preferable?
    and can u explain which method is use in which time?

    ReplyDelete
    Replies
    1. most preferred method is to use service/factory file

      Delete
  11. I dont like the examples.
    The WATCH one for example is watching a rootscope variable!!! If it can do that it can read them anyway -there is no need for the watch.

    The best way to communicate between controllers in REAL TIME is using BROADCAST or EMIT

    ReplyDelete