Get EJS data on an Angular controller

I am trying to transfer data from my node server using ejs to my angular controller so that I can have it available when the controller boots up (not interested in angular or the UI router, where you can allow it).

Node server (using express):

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

Angular:

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

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

If this is not possible, I would like to hear suggestions on how to have preloaded data on my page.

+7
angularjs ejs
source share
1 answer

I would pass a string version of the array and then parse it on the client:

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

And don't forget to specify it (this assumes your controller is on your EJS page)!

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

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

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

And analyze:

 $scope.init = function(stringifiedArray) { var info = JSON.parse(stringifiedArray); } 
+8
source share

All Articles