Skip to content

Instantly share code, notes, and snippets.

@logikinc
Last active August 29, 2015 14:15
Show Gist options
  • Save logikinc/8ef3e7d3a21577224e66 to your computer and use it in GitHub Desktop.
Save logikinc/8ef3e7d3a21577224e66 to your computer and use it in GitHub Desktop.
AngularJS Good Factory Default Snippet
var app = angular.module('app', []);
app.controller('Ctrl1', function(DataFactory) {
this.items = DataFactory.items;
DataFactory.getDataStream();
});
app.controller('Ctrl2', function($timeout, DataFactory) {
// when this eventually fires and gets *remote* data again
// our other controller will automatically sync up
// without the need for the $watch function
$timeout(DataFactory.getDataStream, 2000);
});
app.factory('DataFactory', function($q) {
var svc = {};
svc.items = [];
svc.getDataStream = function() {
var fakeData = [
{ id: 1, name: 'name 1' },
{ id: 2, name: 'name 2' },
{ id: 4, name: 'name 4' }
];
// using $q to fake async data grab
return $q.when(fakeData)
.then(function(data) {
// this is the magic
angular.copy(data, svc.items);
});
};
return svc;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment