2

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?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Josh, a great help indeed and +1 for identifying the root of my confusion :)
-1

Jade variables can be accessed in Angular by assigning interpolated value to a variable in ng-init

First you have to stringify the user and then interpolate using #{value} div(ng-init = 'angularUser = #{JSON.stringify(user)}')

In this situation the user variable is a Jade variable

1 Comment

please read this: stackoverflow.com/help/how-to-answer to help you write and format your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.