Using AngularJS html5mode with express.js - javascript

Client-side:
when("/page/:id", {
templateUrl: "partials/note-tpl.html",
controller : "AppPageController"
});
$locationProvider.html5Mode( true );
Html:
<a ng-href="/page/{{Page._id}}">{{Page.name}}</a>
Server-side:
app.use("/page/:id", function( req, res ) {
res.send( req.params )
});
As a result I get empty page or just object with id. What's wrong?
Angular does not load note-tpl.html template

Might be because of the conflict from express templating engine vs angular.
What view engine are you using?
The use of {{}} might be handled by express and not angular. You can either change the server view engine to use other keywords.

Sounds like your server is not responding with note-tpl.html.
Are you sure your partials exist at that path? Have you used express.static?
Can help more with any error messages you get.

Related

NodeJS - AngularJS Send JSON object and render templat at same time?

I have some problems with my api.
I use NodeJS with ExpressJS Routing and AngularJS.
What I want to do is to render a template (ejs) and at the same time send a json object.
In my routes folder I have the index.js file with this (a little part) :
router.get('/data', function(req, res, next){
Planning.getPlanningM(function(resultat){
res.json(resultat);
res.render('index');
});
});
About the variable resultat I'm sure that it contains that I want. But I can't do the res.json and the res.render. Because of the two invoke of send function.
And in my angular I have this in a function :
var resultat = []
$http.get('/data')
.success(function(res){
angular.extend(resultat, res.data);
})
.error(function(res){
console.log('err');
})
return resultat;
The goal is to render my index.ejs and to show my planning in this page. But I find no solution to do this.
This is my first ask on stackoverflow, english is not my native language. Please don't be rude with me :)
I'm not familiar with EJS, I use handlebars, but you should be able to pass data in the render function like so-
...
res.render("index", { data:resultat });
...
Then access it in the template in whatever format EJS uses. For hbs it would look something like
...
<div>My data looks like this: {{data}}</div>
...
Again, EJS is sure to do it differently, refer to the doc to ensure you have the correct format.
Thanks for your answer MPawlak !It helped me !
That I want is to send the data with the render like you do yes.
But I want to grab/take this data in my angular Factory (my factory fills the controller, this part works) that I show before :
var resultat = []
$http.get('/data')
.success(function(res){
angular.extend(resultat, res.data);
})
.error(function(res){
console.log('err');
})
return resultat;
With your method, I can take this data into my view directly your right and it's works ! Thanks !
<pre> <%= data %> </pre>
So I was thinking about a dirty temporaly solution to do this:
<textarea ng-model="planning"> <%= data %> </textarea>
But when I want to show this planning it don't work and stay empty... I don't understand why.
But to get a good and clean solution I think this is not a good idea, so my ask is the same... how to take this data in my angular factory directly ?

In Angularjs how do I load the same javascript file but pass different keys for different environment (Test, beta, prod)

in Angularjs in a html page I need to load an external javascript file:
<script src="https://www.my-url.com/js/my.js?Key=xxxxxxxx"></script>
But based on different env (test, beta, prod), I will have different Key.
How can I implement this like what we usually do using web.config in .net?
Edit:
I saw some answers, but seems not exactly what I need. so I elaborate my environment: I have a client side which is pure html and Angularjs, my server side is an Asp.net Web API web service. When I talk about web.config in the original post, I don't mean put the key in web.config, but something conceptually similar. I want this "config file" on the client side, not on my Web API.
You can use gulp-replace and automate it on your build time.
There are two issues to solve:
Getting web.config values into the angular app
Making use of the config to download a script
1. Getting web.config to the app:
I've detailed in a blog post the method I use. Essentially, use a custom angular provider in the applications .cshtml file. This will load all web.config items with the prefix of client:...
Used by the MVC controller:
public static class ApplicationConfiguration
{
private const string ClientAppSettingPrefix = "client:";
public static object GetClientConfiguration()
{
var clientConfiguration = new ExpandoObject() as IDictionary<string, Object>;
// Find all appSetting entries prefixed with "client:"
foreach (var key in ConfigurationManager.AppSettings.AllKeys.Where(key => key.StartsWith(ClientAppSettingPrefix)))
{
// Remove the "client:" prefix before adding to clientConfiguration
clientConfiguration.Add(key.Replace(ClientAppSettingPrefix, String.Empty), ConfigurationManager.AppSettings[key]);
}
return clientConfiguration;
}
}
Script added into the app's .cshtml file:
<!-- Inject the configuration -->
<script type="text/javascript">
(function() {
angular.module('client.config', [])
.provider('applicationConfiguration', function() {
var config = #Html.Raw(JsonConvert.SerializeObject(Model, new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()}));
return {
config: config,
$get: function() {
return config;
}
};
});
})();
</script>
So now you can use it in you add as a normal dependency:
angular.module('app', [
// Add as a dependent module
'client.config'
])
.config([
'applicationConfigurationProvider', 'dataServiceProvider', function(applicationConfigurationProvider, dataServiceProvider) {
// Set the api root server configuration
dataServiceProvider.setApiRootUrl(applicationConfigurationProvider.config.apiRoot);
}
]);
2. Making use of config to download script
As suggested in other answers, use JQuery's getScript() function.
Other SO answers also suggest using a simple injection into the head if you don't want to depend on Jquery. Take a look at Single page application - load js file dynamically based on partial view for ideas
You have couple of options here.
Option 1:
Use Angular's http service to get script files dynamically as String and then use eval() function to execute resulting String.
References: eval Angular $http service
Option 2:
Use JQuery's getScript method
Example:
var keys={ 'prod':'prodKey',
'staging:='stagingKey',
'dev':'devKey'
}
//Assuming you have an variable storing modes like prod, staging or dev
var url='https://www.my-url.com/js/my.js?Key='+keys[ENVT.MODE];
$.getScript( url, function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Script loaded successfully" );
});
Reference: getScript

Can't Render EJS Template on Client

I'm coding an application on express, and I'm using ejs as a view/template engine.
At path /artists, I'm rendering the view artists.ejs which has artists covers. When clicking on a cover, I want an AJAX call to retrieve the corresponding data, place it in my template/view for artist artist.ejs and display this template in my HTML under the cover.
I've seen this related question but it has not solved my use case.
Everything seems clear, but I can't render the data with the template. I would like to compile the template server-side, send it to the client ready to use, and then fill it in when needed with the data received from the AJAX call.
What I've done:
When calling /artists, compile on server-side using ejs.compile(str, opt):
router.get('/artists', function(req, res) {
// Compile artist template
fs.readFile('views/artist.ejs', "utf-8", function(err, template) { // Convert template file to string
artist_template = ejs.compile(template); // Compile template
res.render('artists.ejs', {template: artist_template}); // render page with compiled template
});
I took care of converting the file into String, as ejs compiler only works with String (compared to Jade .compileFile)
Then on client-side, I grab the function:
<script>
var template = <%= template %>
</script>
Then on another script, I retrieve the data with an AJAX call:
$.get('/artists/'+artist_name, function(data) {
var html = template({artist: data});
$('#artist-page').html(html);
}
But when I make the call, I receive:
Uncaught ReferenceError: fn is not defined
When I call the template, fn, I receive:
Uncaught ReferenceError: opts is not defined.
Is the function fn hard-coded? I've read the EJS and Jade documentation but there was little relevant information in regards to my issue.
Do I perhaps need the template on client-side also?
I eventually found a workaround to my question, and I understood with your answer that you could proceed in 2 different ways:
1) What I did: read and save template as a string, then render it client-side with ejs Runtime script.
// In controller.js
var templates = {};
templates.template1 = fs.readFileSync(filePath1, 'utf-8'); // Read template as a string
templates.template2 = fs.readFileSync(filePath2, 'utf-8');
...
res.render('app.ejs', {templates: templates}); // Send templates in view
// In view app.ejs
<script type="text/javascript">
var templates = <%- JSON.stringify(templates) %>; // Get templates object (object of strings)
</script>
<script type="text/javascript" src="/JS/ejs.min.js"></script> <!-- Load ejs RunTime -->
// In site.js - javascript client/public file
$.get('/artists', function(data) {
var html = ejs.render(templates.template1, data); // Render ejs client side with EJS script (template1 corresponds to the artists template)
$('#artists-wrapper').html(html); // Sets HTML
});
Thus, I send all my templates on first page load, and then I render the requested page on the client side. The interest, according to what I've read, is that you only send JSON object (your data) through AJAX calls, and not the entire page, making your request light. Only the first load is heavy with all your templates.
2) What I would like to do according to #RyanZim answer: compiling templates server side into functions, send them, and then call them on the client side : template(data). If I understood well, there is no need of EJS client library in this case, and my templates are no longer strings but functions:
// In controller.js
var templates = {};
templates.template1 = ejs.compile(fs.readFileSync(filePath1, 'utf-8'), {client: true}); // Get template as a function
templates.template2 = ejs.compile(fs.readFileSync(filePath2, 'utf-8'), {client: true});
...
res.render('app.ejs', {templates: templates}); // Send templates in view
However, I can't get them in my view:
<script type="text/javascript">
var templates = <%- JSON.stringify(templates) %>; // Get templates object (object of functions)
</script>
is not working. they are functions on the server before I send them, but I don't know how to recover them. Do you have an idea ?
I tried a workaround, by changing them into String before sending them:
templates.template1 = templates.template1.toString();
Send them and then client side, transform them back in functions:
var template = new Function(templates.template1);
$.get('/artists', function(data) {
var html = template(data);
$('#artists-wrapper').html(html); // Sets HTML
});
But that won't work either.
Do you have an idea what I'm missing here?
And last, do you agree that compiling them server side before using the functions is better in terms of computation than rendering each template client-side?
Thanks for the help, and hope that will help anybody else!
You need to use the client option on the server side when you are compiling for the client. From the docs:
client When true, compiles a function that can be rendered
in the browser without needing to load the EJS Runtime
https://github.com/mde/ejs#options
Your server-side code snippet should be:
// Compile artist template
fs.readFile('views/artist.ejs', "utf-8", function(err, template) {
artist_template = ejs.compile(template, {client: true}); // Use client option
res.render('artists.ejs', {template: artist_template});
});

unable to pass data from js to jade in node.js

I am reading a row from a table(emp) in cassandra.
I am trying to pass the result from js file to jade file to present the data on the user interface.
I have the js function as below
router.get('/cassandra', function (req, res)
{
client.connect(function(err){
});
client.execute('SELECT * FROM monica.emp WHERE empid= 324;', function (err, result) {
var user = result.rows[0];
console.log("here is the user", user.empid, user.firstname);
res.render('cassandra',{"cassandra":user});
});
});
my log is reading the result. But i am unable to pass the same to the UI from the jade file.
Below is my Jade File
extends layout
block content
p Cassandra
for i in cassandra
.c=i.empid+" "+i.deptid
I am getting a display something like below
Can someone please help me with where I am going wrong over here?
Looks like user is not an array. So just try cassandra.empid without a loop in the jade view
You might need to use a promise. Are you trying to render the template before the response comes back from the server?
try it
-for(var i in cassandra){
.c=#{cassandra[i].empid}+" "+#{cassandra[i].deptid}
-}
Your jade file should read
extends layout
block content
p Cassandra
#{cassandra.empid} #{cassandra.deptid}

Simple routing and unobtrusive template engine in Node JS

This is a multi part question and I'm a complete newbie to Node so please be gentle:)
I have a very simple Node/express app set up returning an index.html without using routing...
var app = express();
var port = process.env.PORT || 1337;
app.use('/i', express.static(__dirname + '/i'));
app.use('/Stylesheets', express.static(__dirname + '/Stylesheets'));
app.use(express.static(__dirname));
app.listen(port);
console.log('listening on port ' + port);
The index.html is served as a static file.
My next job is to start returning a few pages with proper routing, I've got as far as working out I need to put my routes in a routes.js file and "require" that file in my server.js file but I can't get my head around setting the routes up and every example/demo I see online seems to do it a different way. Any definitive examples of how to do this would really be appreciated.
The next part of the problem is that I want to include dynamic pages but don't know where to go with templating engines. I would like to use something "unobtrusive" so that my original HTML files still make sense when viewed in a browser.
On the front-end I would simply inject HTML into the page by first using a selector and then using the .html() method to alter the html, I could bind JSON data with a template and then inject it into the right place by looking for a classname etc. THis would be totally unobtrusive and wouldn't require any ugly {} brackets, inline javascript or directives. Psuedo code...
var data = {"name":"John"};
var result = templateEngine.bind("/template.html", data)
$('.person').html(result);
That way, I could keep my original HTML clean and viewable, like this...
<div class="person">
My Name is FirstName
</div>
The closest thing I can find is PURE - http://beebole.com/pure - but I'm not sure how to get it working with NODE (or even if it's compatible).
To add more complexity, whatever templating engine I use needs to be able to use sub-templates(partials?) so that I can include a header/footer etc which is te same on every page. I assume this can be done recursively by referencing sub-templates from within each main template where needed?
If you're still reading this then clearly you'll have worked out that I'm floundering here with a new technology and any help would be really appreciated!
but I can't get my head around setting the routes up and every
example/demo I see online seems to do it a different way. Any
definitive examples of how to do this would really be appreciated.
Not sure what you have seen different in the examples, but the general pattern is like this:
app.**[HTTP VERB]**(**[URL]**, function(req, res){
res.end('<html>hello world</html>');
});
The following code will accept all HTTP GET requests to the root URL of your site:
app.get('/', function(req, res){
res.end('<html>hello world</html>');
});
While the following code will accept all HTTP GET request to /test in your site
app.get('/test', function(req, res){
res.end('<html>hello world from the test folder</html>');
});
It's common to have a separate route for HTTP POST requests (e.g. when the user submits data back to the server). In this case the HTTP verb is POST as in the following example.
app.post('/test', function(req, res){
res.end('<html>Thanks for submitting your info</html>');
});
In this case I am embedding the code to handle the request directly rather than referencing an external routes.js as you indicated just to make the examples cleaner in this question. In a real application you'll do it by referencing an external function so that your app.js stays lean and clean.
app.get('/test', routes.NameOfFunctionToHandleGetForSlashTest);
app.post('/test', routes.NameOfFunctionToHandlePostForSlashTest);
I know this is an old question, but I have explored this topic recently, and came up with the following solution:
my original question
I have placed the following configuration on ejs:
var ejs = require('ejs');
server.configure(function(){
server.set("view options", {layout: false});
server.engine('html', require('ejs').renderFile);
server.use(server.router);
server.set('view engine', 'html');
server.set('views', __dirname + "/www");
});
This sets your view engine as ejs, your view directory as your static public html directory and tells ejs to process .html files as opposed to .ejs.
The routes can be handles like this:
server.all("*", function(req, res, next) {
var request = req.params[0];
if((request.substr(0, 1) === "/")&&(request.substr(request.length - 4) === "html")) {
request = request.substr(1);
res.render(request);
} else {
next();
}
});
server.use(express.static(__dirname + '/www'));
This routes all html requests through the view engine, and passes all other requests on down the stack to be sent as static files.
Your html can now look something like:
<%include head.html%>
<%include header.html%>
<p class="well">Hello world!</p>
<%include footer.html%>
you can have nested includes, and pass variables down into your includes. So for instance your include head can call:
<title> <%= title %> </title>
and at the top of your index page you can include an object like:
{var title: "Home"}
Anyway, maybe this will help out someone who is looking for a ultra easy way to handle includes while sticking with normal html.

Categories