Sumit Chaudhari
Sumit Chaudhari

Reputation: 210

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 ?

Upvotes: 0

Views: 64

Answers (2)

jimmygchen
jimmygchen

Reputation: 795

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

Upvotes: 3

npr
npr

Reputation: 4765

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

Upvotes: 1

Related Questions