Skip to content

Instantly share code, notes, and snippets.

@rguruprakash
Created February 26, 2017 13:59
Show Gist options
  • Save rguruprakash/c669956f56a7ff2e0ef6c69ca09f9015 to your computer and use it in GitHub Desktop.
Save rguruprakash/c669956f56a7ff2e0ef6c69ca09f9015 to your computer and use it in GitHub Desktop.
AngularJS: Share data between controllers with Service and Watchers
var myModule = angular.module('myModule', []);
myModule
.service('dataService', function($parse) {
var self = this;
return {
setData: function(data) {
self.data = data;
},
getData: function() {
return self.data;
},
bind: function(expr, scope) {
var getter = $parse(expr);
var setter = getter.assign;
scope.$watch(function() {
return getter(self);
}, function() {
setter(scope, getter(self))
});
}
};
});
myModule
.controller('controller1', function($scope, dataService) {
dataService.bind('data', $scope);
$scope.setData = function() {
dataService.setData('Controller 1');
};
});
myModule
.controller('controller2', function($scope, dataService) {
dataService.bind('data', $scope);
$scope.setData = function() {
dataService.setData('Controller 2');
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment