Created
February 26, 2017 13:59
-
-
Save rguruprakash/c669956f56a7ff2e0ef6c69ca09f9015 to your computer and use it in GitHub Desktop.
AngularJS: Share data between controllers with Service and Watchers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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