i'm currently trying to display the name of the logged-in user in my MEAN app. I'm using the EJS templating engine and I'm able to get the username showing by putting <%- user.username %> in my markup. The problem with this is that I don't really want to my mixing angular and embedded scripts in the same files, I'd like to pass the server-side data into Angular. I've tried ng-init but I'm not having any success at all with it.
3 Answers
I will assume you are using ExpressJS 4 it will be a little different in version 3, however the approach will be the same for both versions:
Node/Sever side
var express = require('express');
var bodyParser = require('body-parser');
var schema = require("./schemas");
var app = express();
var router = express.Router();
router.get('api/account', function(req, res){
res.json({ "login": req.session.user.login }); /*access the session account not sure if this matches your login location you will adapt it to your own*/
});
Angular/Client Side
You then invoke from your controller or service the url api/account with a GET request to receive the JSON like:
$http.get("/api/account").then(function(data){ console.log(data); });
then you could do something like:
$scope.login = data.login;
and in the html
{{login}}
3 Comments
data in the callback is actually an object with multiple properties such as headers, status, and data. So I think the code in the answer should be adjusted.success or error method it's as you say, but with the then method it's different. From the section called Returns: "The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties: data – {string|Object} – The response body transformed with the transform functions..."From what I understand of Angular, it discourages server-side setting of templated values in HTML code. Consider setting up a JSON service that provides the data, and fetching the data over JSON. There is an example at the end of the Angular Tutorial that may make this clearer.
1 Comment
I do the exact same thing and mix EJS to embed things like my server info (to initiate a socket connection from the client). If you wanted to keep this purely client-side, you would need to have AngularJS fetch the server-side data using a service / factory - and then affect any views you have depending on said data.
ng-init only applies to things which live inside the "Angular" scope.