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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With