Accessing Get variable in Angular function


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?


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.

By : James M

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) {

and then in my angular controller...

function profileCtrl($scope, $http) {

  $http.get('/api/user/').success(function(data) {
    $scope.user = data;

This is an old post but a relevant one. Zemrico's answers is good but needs to be updated as there are some changes to the jade/pug syntax. Firstly, the link in his answer is broken and should be

If you are reading the blog post, please note that the following no longer works as pug no longer accept interpolation as an attribute.

div(ng-controller="UserCtrl", ng-init="user= #{JSON.stringify(user)}")

Instead, please use this.

div(ng-controller="UserCtrl", ng-init="user="   JSON.stringify(user) )
By : Sydney

This video can help you solving your question :)
By: admin