7

I'm trying to pass data from my node server using ejs to my angular controller so that I can have it available when the controller loads (not interested in Angular or UI router where you can have resolves).

Node server (using express):

app.get('/', function(req, res) {
  res.render('index', {
    names: ["Daniel", "Sarah", "Peter"]
  });
});

Angular controller:

.controller('NamesController', function ($scope) {
  var info = <%= names %>;
});

Doing this gives me the following error: Uncaught SyntaxError: Unexpected token <

If this is not possible, I'd love to hear suggestions on how to have pre-loaded data on my page.

1 Answer 1

8

I'd pass a stringified version of the array in - then parse it out on the client:

app.get('/', function(req, res) {
    res.render('index', {
        names: JSON.stringify(["Daniel", "Sarah", "Peter"])
    });
});

And remember to quote it (This assumes your controller is in your EJS page)!

.controller('NamesController', function ($scope) {
    var info = JSON.parse('<%= names %>');
});

If your controller is in your own file, you can use an ngInit method:

<div ng-init="init('<%= names %>')"></div>

And parse:

$scope.init = function(stringifiedArray) {
    var info = JSON.parse(stringifiedArray);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Nice. I got it to work with ng-init, but I'm curious to see why I can't get it to work the other way.The controller is loaded through ng-controller on the parent div of my ejs file -- which is loaded through an ejs include on another ejs file. Thoughts on why that wouldn't work?
@DanielFalabella -- So the JavaScript is inside the EJS file, right?
Are you quoting the variable when you try and write it in? var data = '<%= var %>';
Yeah: var info = JSON.parse('<%= names %>'); . I still get this error: Unexpected token <

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.