Access global variable in angular

I am using node express and angular. In my express app.js, I declare a route and pass a variable to the rendered page, like so...

app.get('/test' function(req, res){
  res.render('test', { user: 12345 });
});

In my 'test' view, I link the container to angular with ng-controller, like so...

<div ng-controller='testCtrl'> <!--some markup here--> </div>

And in my angular controllers.js, I declare a function for my view, like so...

function testCtrl($scope) {
    /*...some code here...*/
}

How can I access the 'user' variable that I passed in to the view from express, inside my controller function?

Because you're using a template to render a view, there are two different executions: (1) your server is rendering a page (using the user var) and then (2) the browser runs AngularJS. So you can't pass a variable from (1) into (2).

However, there is a directive called ngInit that will parse an expression during bootstrap. If you're using Jade templates in ExpressJS, you could do something like this:

div(ng-init='user = "'+user+'"')

Which would render the HTML like so:

<div ng-init="user = 'whatever-server-sent'"></div>

So when AngularJS bootstraps this part of the page (or this partial or template) then user will become a scope variable with the value from the server.

I didn't test the Jade code and I'm not a Jade expert, but this should put you on the right track. If you're using a different templating engine, let me know and I'll revise the answer.