Express Pass Variable to Angular Without Templating Engine - angularjs

Question: Does this work without e.g. ejs/jade? And where is the difference between a framework like AngularJs and a templating engine?
E.g.
Server.js
var express = require('express');
var app = express();
Routes.js
app.get('/', function(req, res) {
// res.render('index.ejs');
res.sendfile('index.html', {
user : "Tom"//req.user
});
});
Index.html (Here I have no idea how to do this)
<body ng-app="App" id="App" ng-controller="RootCtrl as rootCtrl" ng-mouseleave="rootCtrl.exit()">
<script>
// angular.module('$user', []).constant('$user', <%= user %>)
</script>
....
Tutorials I looked into:
http://www.mircozeiss.com/how-to-pass-javascript-variables-from-a-server-to-angular/
http://www.linkplugapp.com/a/224929

Yes this should work, but you need to enable ejs in your express app.
app.set('view engine', 'ejs');
I did the same thing with laravel and blade.

Related

How to separate angular + ejs app from node

I have web application which is developed using ejs + angularJs 1.0 and running in node server. Since these ejs + angular provides only static files, I want to make my app running in webserver. Currently the URL mapping is done in node app.js, hence if we load the URL it renders the html from the ejs. For more information, I have added node app.js configuration:
app.set('title', wsConfig.title);
app.use(bodyParser.json());
app.engine('.html', ejs.__express);
app.set('view engine', 'ejs');
app.use(express.static('./public'));
app.set('views', path.join(__dirname, 'public')); // Set the views path
app.use(function(req, res, next) {
if (req.url.substr(-1) == '/' && req.url.length > 1)
res.redirect(301, req.url.slice(0, -1));
else
next();
});
app.get('/', function(req, res) {
res.render('login', { title: wsConfig.title });
});
app.get('/home', function(req, res) {
res.render('index', { title: wsConfig.title });
});
Hence I need to build a dist folder with js and rendered ejs files instead using node server for rendering. So that I will deploy this dist directory in web server. I thought of using webpack to accomplish this. Please give our suggestions.

Angular js Expressions not working in Node js project

I have configure node js default project with express and using HTML page instead of JADE. I want to use Angular JS within HTML pages. Angular JS Simple examples are working fine in this project as :
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
Its working Fine. But if i am using {{name}} instead of ng-bind="name", its not working in this project.
For Example:
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
This is not working in node project. Can anyone help me to find-out the issue.
App.js File code is as following:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Sql server new code
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
var webconfig = {
user: 'sa',
password: '#####',
server: '######',
database: 'Test_Training',
options: {
encrypt: false // Use this if you're on Windows Azure
}
}
var sql = require('mssql');
// Sql server new code
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// To use simple html page
var cons = require('consolidate');
// view engine setup
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// To use simple html page
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/public'));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Help will be appreciated.
The html engine is not supported out of the box.
(ref: https://github.com/expressjs/express/wiki#template-engines)
Solution given by #Thanh Tùng will work, but if you really want to set html as a view engine you should follow this solution
app.set('views', path.join(__dirname, 'views'));
// Set EJS View Engine
app.set('view engine','html');
// Set HTML engine
app.engine('html', require('ejs').renderFile);
Later you need to place your index.html inside /views directory
(original answer: https://stackoverflow.com/a/44945104/3627827)
EDIT: updated answer as suggested by #DanielZiga
First remove it :
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
I'm not sure about your strug folder but I guess file index.html of you in folder public . Try add this code in your node :
app.get('/*',function(req,res){
res.sendFile( index.html,{root:path.join(__dirname,public/index.html)});
})
You are using Swig as a Template Engine for your Server Side Rendering.
As you can see in its doc, Swig uses {{ and }} as interpolation delimiters... they're the same used by AngularJS.
What could happen is that Swig doesn't let your raw html reach the angular...
Try to change interpolation delimiters:
// https://docs.angularjs.org/api/ng/provider/$interpolateProvider
angular
.module('ModuleName')
.config(['$interpolateProvider', function($interpolateProvider) {
// set start symbol here
$interpolateProvider.startSymbol('^_^');
// set end symbol here
$interpolateProvider.endSymbol('"_"');
}])
;

AngularJS: File upload

I am a newbie of angularjs. My version is 1.6.4 using with nodeJS. I am following this tutorial for file upload leon/angular-upload. I did all the steps written here to make it work which are.
1) bower install --save angular-upload
2) Add module dependency "lr.upload" which i did
angular.module(__appName, ["ngMap", "multipleSelect", "lr.upload"]);
3) Add this code snippet in html page, so i did in my fileupload.html.
<div class="btn btn-primary btn-upload"
upload-button
url="/upload"
on-success="onSuccess(response)"
on-error="onError(response)">Upload</div>
4) And finally add script to html page.
<script src='bower_components/angular-upload/angular-upload.min.js'></script>
But i am still getting error:
POST http://localhost:3000/upload 404 (Not Found)
My server.js is code is:
var express = require("express");
var app = express();
app.use(express.static(__dirname + '/app'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get("/", function(req, res){
res.redirect("app/index.html");
});
app.listen(3000, function(){
console.log("Tellworld web app listening on port 3000");
})
Here is Server.JS files that you should follow
https://github.com/leon/angular-upload/blob/master/example/server.js
You have to add :
app.post('/upload', function(req, res) { /*do your post processing here */ })
Your server will also need it route that receive request from the angular's route directive. In clear english you will need to declare a route pointing to upload in your server which may look like the code below
app.post('/upload', function(req, res){
console.log(req.body); //this is just to show the request body on your console
});

Using Jade and Handlebars together and rendering accordingly

I am trying to understand how to include jade and handlebar exactly as I am trying to add angular js to my server that is also using jade for serving other web pages.
I heard of consolidate.js and this is my app.js code:
var engines = require('consolidate');
var exphbs = require('express-handlebars');
var app = express();
app.engine('jade', engines.jade);
app.engine('handlebars', engines.handlebars);
app.set('view engine', 'handlebars');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(path.join(__dirname, 'public', 'img/favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser(config.cookieSecret.secret));
app.use(express.static(path.join(__dirname, 'public')));
How do I get the view engine setup for both? Also, how do I add the following into my code without affecting other links:
// Application UI route
app.get('*', function(req, res) {
res.render('indexer');
});
app.get('/templates/*', function(req, res) {
res.render('../client/templates/' + req.params[0])
});

What is the proper way to set up Express routing with HTML files when using the ng-boilerplate kickstarter?

I'm struggling to perform routing using Express in the ng-boilerplate structure.
I'd like to do it using HTML view files (as opposed to JADE).
Can anyone help provide examples of how to do this?
I keep getting Failed to lookup view xx errors when using app.get('/', function(req, res){
res.render('index');
});
Try to set your views directory:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views'); // <=== Where your HTML view files are present
app.set('view engine', 'jade'); //Your view engine to be set here
});
For detailed information:
Express API
Related Questions and answers

Resources