Skip to content

Instantly share code, notes, and snippets.

@NelsonBrandao
Created April 16, 2015 10:47
Show Gist options
  • Save NelsonBrandao/957cd19df43f4e50158f to your computer and use it in GitHub Desktop.
Save NelsonBrandao/957cd19df43f4e50158f to your computer and use it in GitHub Desktop.
Service for sharing the current user logged user between multiple controllers
angular.module('app')
.factory('CurrentUserService', [
'$q', '$rootScope', 'UserService',
($q, $rootScope, UserService)->
myService = {}
myService._initialized = false
myService.refresh = ->
# Create the defer to promise data
deferred = $q.defer()
# Get the data from the API
UserService.get_current_user().then((current_user)->
# Return the promised content
deferred.resolve(current_user)
if myService._initialized
$rootScope.$broadcast('newCurrentUser', deferred.promise)
myService._initialized = true
)
# Promise the data
myService.current_user = deferred.promise
return deferred.promise
myService.refresh()
return myService
])
angular.module('app').controller("ExampleCtrl", [
'$scope', 'CurrentUserService', 'UserService',
($scope, CurrentUserService, UserService) ->
original = {}
CurrentUserService.current_user.then((current_user) ->
original = angular.copy(current_user)
$scope.current_user = current_user
$scope.user = current_user
)
$scope.updateUser = () ->
# Update the user here
# To refresh the current user do
CurrentUserService.refresh()
])
angular.module('app')
.factory('UserService', [
'Restangular', 'User',
(Restangular, User) ->
model = 'users'
Restangular.setBaseUrl('/api/v1')
Restangular.extendModel(model, (obj)->
angular.extend(obj, User)
)
Restangular.setRestangularFields {
id: "username"
}
get_current_user: ->
Restangular.all(model).get('logged_user')
get: (username) ->
Restangular.one(model, username).get()
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment