I've been trying to get user data from a rails controller to an angular controller:
In my application.html.erb
, I define User
like so:
angular.element(document).ready(function() {
angular.module('myModule').value('User', <%= @user.to_json.html_safe %>);
});
In my angular controller:
myModule.controller('MyController', ['$scope', 'User', function($scope, User) {
$scope.user = User;
}]);
The problem with this is that it exposes the user data to the view. Is there a better way to do this?
I've also tried this approach:
In my module, I created a factory with a $resource object:
myModule.factory('User', function($resource) {
return $resource('/users/:action', {},
{
'getUser': { method: 'GET', params: { action: 'fetch_user.json' }, isArray:true }
});
});
In my controller:
myModule.controller('MyController', ['$scope', 'User', function($scope, User) {
$scope.user = User.getUser();
// Also tried the following.
// This will throw undefined errors in places that are trying to access $scope.user
User.getUser({}, function(data) {
$scope.user = data;
});
}]);
However, this either does not load the user data on time and is throwing undefined
errors throughout my application or it will put every character of the result in it's own array container.
The @user
variable is being returned as json from the server in the users_controller.rb
so ideally, I would want to retrieve that and store it in $scope.user
. The problem with this is that it requires the username
to be passed as a parameter to retrieve the correct user's data.
How can I set $scope.user
correctly and cleanly without exposing data?