How to pass data from EJS template to AngularJS controller

I have custom data from ExpressJS via NodeJS as shown below:

app.js

app.get('/user', function(req, res) {
    res.render('users', { title: 'Foo', user: req.user });
});

      

users.ejs

<%= user %>

      

I need data user

from user.ejs

above to angularjs controller, so I could display this on other named views.

Can anyone help me with this?

+3


source to share


2 answers


Some say ng-init , but that just seems messy and wrong to me. You can put it on a string and mess with the window and root , but it can get messy. Or you can add another module like:

<script>
   angular.module('PreloadedData', [])
     .constant('User', <%- user %>);
</script>

      



It will then be available like any other dependency.

+5


source


try this on template...

<% if(title){ %>
 <script>
window.Mytitle = <%- JSON.stringify(title) %>;
</sript>
<% } %>

try on your controller..
console.log(window.Mytitle);

      

================================================ =



try this on template...

<% if(user){ %>
<script>
  window.MyUser = {};
  window.MyUser = <%- JSON.stringify(user) %>;
</sript>
<% } %>

try on your controller..
console.log(window.MyUser);

      

sorry if i'm wrong ..

0


source







All Articles