Skip to content

Instantly share code, notes, and snippets.

@JAndritsch
Created January 14, 2014 22:35
Show Gist options
  • Save JAndritsch/8427309 to your computer and use it in GitHub Desktop.
Save JAndritsch/8427309 to your computer and use it in GitHub Desktop.
A sample Angular app that fetches data from an API through a Poller service, caches it on another Service, then shows the latest data in the UI
# data resource
angular.module('resources').factory 'DataResource', ['$resource', (resource) ->
resource '/api/v1/data/:id',
{ id: '@id' },
get: { method: 'GET', isArray: false },
query: { method: 'GET', isArray: true }
]
# data service
angular.module('services').factory 'DataService', ['DataResource', (DataResource) ->
currentData = []
class DataService
# simple wrapper to fetch data via the resource, which calls the API
@query: (data, success, failure) =>
DataResource.query(data, success, failure)
@currentData: =>
currentData
@setCurrentData: (data) =>
currentData = data
return new DataService()
]
# poller
angular.module('services').factory 'Poller', [ ->
class Poller
beginPolling: (someService) ->
intervalId = setInterval(->
someService.query(
{},
(response) ->
someService.setCurrentData(response.data)
(response) -> #failure
)
, 3000)
return new Poller()
]
# controller
angular.module('controllers').factory 'DataController', ['$scope', 'DataService', 'Poller', (scope, DataService, Poller) ->
# runs when the controller is initialized
scope.init = ->
Poller.beginPolling(DataService)
# If you don't make this a function, it will only ever have the data that was
# returned from the service at the time of initialization
scope.data = -> DataService.currentData()
# Example: (this is bad...it will only ever be set to whatever your service returned
# the first time your controller was initialized.
scope.data = DataService.currentData()
# Alternatively, you can expose the entire service to your scope and access it
# directly.
scope.service = DataService
]
# view (using a controller method that wraps the service)
div ng-controller="DataController" ng-init="init()"
h1 My Data
ul
li ng-repeat="item in data()"
# view (using the service directly exposed to the scope)
div ng-controller="DataController" ng-init="init()"
h1 My Data
ul
li ng-repeat="item in service.currentData()"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment