Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get EJS data on Angular controller

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.

like image 370
Daniel Falabella Avatar asked Oct 16 '15 15:10

Daniel Falabella


1 Answers

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);
}
like image 132
tymeJV Avatar answered Oct 23 '22 05:10

tymeJV