I'm building an app in node express and angular js. I pass a variable to my view, as follows...
app.get('/profile', ensureAuthenticated, function(req, res){
res.render('profile', { user: req.user });
});
I can access the variable in my view like this (jade)...
h1 #{user}
But how can I access this variable from an angular function in a controller or directive?
I wrote a blog post about this topic - How to pass JavaScript Variables from a server to Angular.
In summary, you've got three options:
You can read about the details in my post and I'll only show the last, and in my opinion smartest, solution.
To pass your user object from your express server to an Angular controller use the ngInit directive:
div(ng-controller="UserCtrl", ng-init="user= #{JSON.stringify(user)}")
That loads the content into Angular scope and you should be able to access it inside your controller by calling $scope.user.
function UserCtrl($scope) {
console.log($scope.user);
}
ng-init is not the way to load/store constants in Angular. Introducing, the Angular way:
<script>
angular.module('$preloaded', []).constant('$preloaded', <%= preloaded %>)
</script>
You can then inject the $preloaded dependency wherever in your code and access the constants.
It sounds to me like you may be mixing things in a not-ideal way. I think the best way to do this is using $resource in the Angular code to call /profile and get the data that way.
Think of it this way, you just used node to create a webservice, now you use AngularJS to call the webservice from your Services layer. The code for calling it is fairly straight-forward and can be found on the documentation I linked.
You may also want to check out the FoodMe demo, this uses node.js as the webservice layer and angularJS as the client-side UI layer in exactly the way you're setting it up.
Thanks James, the FoodMe demo looks like a great learning resource. Having read your reply, it shifted my thinking enough for me to come up with my own solution. I will add it as an alternative answer, simply because code in comments suck. For the sake of improving my understanding of how node and angular can work together, perhaps you or somebody else might be kind enough to comment on how our two solutions compare, and why or when one might be preferable.
In my express app.js...
app.get('/api/user', api.user);
and in my routes/api.js...
exports.user = function (req, res) {
res.json(req.user);
};
and then in my angular controller...
function profileCtrl($scope, $http) {
$http.get('/api/user/').success(function(data) {
$scope.user = data;
});
}