0

I have two parallel controllers headerCtrl and cartCtrl . when I add a product from cartCtrl I want to reflect the count increase in headerCtrl . What is the best way to achieve this ?

I know Using shared services we can achieve this : when a product got added update the count in service . but how can I update the count in headerCtrl ?

Also if there is any other best approach to achieve this ?

Sumit Chaudhari
  • 210
  • 1
  • 15

2 Answers2

3

Usually I'd use service to share data between controllers. So you create a service like below and access/modify it from both controllers. To notify other components, you can use $rootScope.$emit to pass the data. This is usually more efficient than $broadcast if you don't need to propagate event to all child scopes. This is a quick way to do it - however you may quickly end up in a situation where every component depends on $rootScope, an alternative is set up listeners through a service: Why do we use $rootScope.$broadcast in AngularJS?

angular.module('app').service('myService', function($rootScope) {
 var count = 0;

 this.increaseCount = function() {
     count++;
     $rootScope.$emit('countUpdated', count);
 }

 this.getCount = function () {
     return count;
 }
});

angular.module('app').controller('HeaderCtrl', ['$rootScope', function($rootScope) {

  $rootScope.$on('countUpdated', function(count) {
    // do your stuff
  });
}])
Community
  • 1
  • 1
jimmygchen
  • 785
  • 4
  • 8
  • How can I call the getCount() from the HeaderCtrl ? Do I need to refresh it ? – Sumit Chaudhari Jul 14 '16 at 13:20
  • yes i can inject it and call the myService.getCount() . But I need to call this function in headerCtrl when a product got added in cartCtrl . So How will I trigger the call ? – Sumit Chaudhari Jul 14 '16 at 13:22
  • emit will work in case of parallel controller as it will emit to the parent controller only I think? – Sumit Chaudhari Jul 14 '16 at 13:28
  • I've updated the code in the answer - if you $emit the event on $rootScope, you can catch it by adding a listener on $rootScope. This is usually better than $broadcast if you don't need to propagate event to all child scopes – jimmygchen Jul 14 '16 at 13:30
1

I guess there are two issues to be tackled here 1. One is share of data : this can be achieved by having a service 2. Another is automatic update at destination controller i.e without calling get. For this use angular broadcast

npr
  • 4,325
  • 4
  • 20
  • 30