Angular: data view service to modify data?

I have a service defined as something like this:

appServices.service('SharedData', function() { var data = {}; function setContacts(contacts) { data.contacts = contacts; }; function getContacts() { return data.contacts; }; return { setContacts: setContacts, getContacts: getContacts }; }); 

In another controller, I access the data as follows:

 $scope.contacts = SharedData.getContacts(); 

All this is good and good, but I would like $scope.contacts be warned and update it every time the data in SharedData changes.

How to do it?

+5
source share
3 answers

Try an explicit view:

$scope.$watch(function() { return SharedData.getContacts(); }, function(newContacts) { // Do something with newContacts. });

If the elements of the collection can change without changing the entire identifier of the collection object (I assume Array or Object ), you need to use $scope.$watchCollection , although this is much slower than regular $watch , so avoid if you can change the entire collection immediately.

Note that a design may be nicer to expose a function to an area that simply returns current contacts:

$scope.getContacts = function() { return SharedData.getContacts(); };

If you need a notification in SharedData , you can enter $rootScope into it and put $watch on it.

+3
source

$rootScope wary of abuse, but that's just what $rootScope for:

 appServices.service('SharedData', function($rootScope) { var data = {}; function setContacts(contacts) { data.contacts = contacts; $rootScope.$broadcast('contacts-changed', contacts); }; ... 

Now, in any area you want, you can register for this event:

 function($scope) { $scope.$on('contacts-changed', function(eventObj) {...}); } 
+3
source

One way to do this is to define a function in your service that allows you to register a callback that is called when you call setContacts ( onContactsUpdated below). This solution is not ideal (for example, it allows you to register only one "handler"), but should get you on the right track. You can configure it if you need to use it in several places.

 appServices.service('SharedData', function() { var data = {}; function setContacts(contacts) { data.contacts = contacts; if(typeof(data.contactsUpdatedCallback) !== "undefined"){ data.contactsUpdatedCallback(); } }; function getContacts() { return data.contacts; }; function onContactsUpdated(callback){ data.contactsUpdatedCallback = callback; }; return { setContacts: setContacts, getContacts: getContacts, onContactsUpdated: onContactsUpdated }; }); 

Then in your controller:

 SharedData.onContactsUpdated(function(){ //do something with updated SharedData.getContacts() }); 
+2
source

All Articles