3

Can you please explain the use use of data services vs the use of $rootScope events.

I have a list of say branches which provides edit functionality. On click of edit button I am broadcasting an event with root scope using

$rootScope.$broadcast('EditBranch', branchID);

This EditBranch event is captured by edit/create controller which fetches the branch details and renders it in a proper edit format.

Other function is I am adding a new branch and I want it to be listed in existing branch list as soon as it is added. the code used is as follows

$rootScope.$broadcast('AddBranch', branchData);   //in create controller

$scope.$on('AddBranch', function(e, branchData){  //in listing controller 
    $scope.branches.push(branchData);
});

Is it right to use $rootScope this way. Or should I create a shredService for sharing branch data after I create it.

Uday Sawant
  • 5,748
  • 3
  • 32
  • 45

2 Answers2

5

It may not be easy to say if one approach is better than the other. However, I would use a shared service in this case since it is all about manipulating the same data, branch (I suppose). $broadcast and $on are more appropriate in situations where different "independent" components of your application could be listening for an event and each of these components could response differently when the event occurs.

kubuntu
  • 2,525
  • 1
  • 22
  • 24
5

Service is a Singleton and you can inject to any controller and invoke getter/setter service values in a controller's scope.

I think with Services you have better control over data and might make code clear.

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
  • I think service is better alternative, it also allow encapsulate the logic into a module (branch) with the related controllers, directives,... and then inject it into any controller (@MaximShoustin) – pdorgambide Mar 10 '14 at 08:55