Last active
August 29, 2015 14:04
-
-
Save huttj/89374261eb8d468bc009 to your computer and use it in GitHub Desktop.
AngularJS pub/sub example
This file contains 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
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