Skip to content

Instantly share code, notes, and snippets.

@huttj
Last active August 29, 2015 14:04
Show Gist options
  • Save huttj/89374261eb8d468bc009 to your computer and use it in GitHub Desktop.
Save huttj/89374261eb8d468bc009 to your computer and use it in GitHub Desktop.
AngularJS pub/sub example
angular.module('app')
.service('dataSvc', function($q) {
var dataStore = [];
// Slight abuse of promises to achieve pub/sub pattern
var updater = $q.defer();
function addData(data) {
// Add the data to the dataStore
dataStore.push(data);
// Tell all subscribers about the update, and
// provide the updated array
updater.notify(dataStore);
}
// Expose the required methods
return {
addData: addData
onUpdate: updater.promise
}
})
.controller('myCtrl', function($scope, dataSvc) {
// $scope.data is a ng-model
// $scope.submit is connected to submit button
$scope.submit = function() {
if ($scope.data) {
dataSvc.push($scope.data);
}
}
})
.controller('anotherCtrl', function($scope, dataSvc) {
// Subscribe to notifications from the dataSvc
dataSvc.onUpdate().then(null, null, function(dataStore) {
$scope.data = dataStore;
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment