Created
April 16, 2015 10:47
-
-
Save NelsonBrandao/957cd19df43f4e50158f to your computer and use it in GitHub Desktop.
Service for sharing the current user logged user between multiple controllers
This file contains hidden or 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') | |
.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 | |
]) |
This file contains hidden or 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').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() | |
]) |
This file contains hidden or 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') | |
.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