Sumit Chaudhari Sumit Chaudhari - 4 months ago 20
AngularJS Question

Angular Js data sharing between controller

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 ?

Answer

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
  });
}])
Comments