How to create own service accessible globally that will call server by currentUser()
only once on page load, if User is logged in then keep it and provide data to c
I solved the issue of current_user information with angular by adding the following JavaScript (jQuery) code to the bottom of my main HTML page:
$("meta[name=current_user]").data('current_user', {
id: <%=j current_user.id.to_s %>,
username: "<%=j current_user.full_name.to_s %>"
});
You can parse in whatever information you need, this happens to be a Rails Project and all I needed was the ID and NAME (with the ID I could query the User factory object and receive a JSON with full information if I needed).
Then in your AngularJS Controller you can add (mine is coffeescript):
# Grab User Info
current_user = angular.element("meta[name=current_user]").data 'current_user'
# Stop Here if you Have the Info you Need
$scope.user = current_user
# **** OR Get More Info if User is Logged In
if current_user.id is not undefined
$scope.user = User.get {id: current_user.id}
Here is my Factory Code for the User (coffeescript again):
# In order to prevent minification from effecting the code
# must wrap functions as arrays and pass in the variables as
# strings before the function call
app.factory "User", ["$resource", ($resource) ->
$resource("/api/angular/users/:id",
{ id: "@id" },
{
update: { method: "PUT" }
})
]
Let me know if you have any questions.