Angular js Expressions not working in Node js project - angularjs

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('"_"');
}])
;

Related

Unable to load css file

I am using express and nunjucks template engine for building a node app.
templateEngine.js
var nunjucks = require('nunjucks');
module.exports = function (app) {
// store environment env
var env = nunjucks.configure(['views/www'], {
autoescape: true,
express : app
});
}
app.js
var express=require('express'),
app=express(),
engines = require('consolidate'),
nunjucks = require('nunjucks');
MongoClient = require('mongodb').MongoClient,
http = require("http"),
assert = require('assert');
require('./templateEngine.js')(app);
app.set('view engine', 'html');
MongoClient.connect("mongodb://localhost:27017/firstDb",function(err,db){
assert.equal(null,err);
console.log("Sucessfully Connected to the Server");
app.get('/',function(req,res){
var query = {name : 'nobody'};
db.collection('friends').find().toArray(function(err,docs){
console.log(docs)
res.render('index',{'friendNames':docs})
})
})
})
var server = app.listen(3000,function(){
var port=server.address().port;
console.log('Express server listening on port', port);
})
When I tried to load
<link href="css/style.css" rel="stylesheet">
in index.html it says cannot get "http://localhost:3000/css/style.css"
my folder structure is
Root
views
www
css
style.css
index.html
app.js
templateEngine.js
If anybody encountered this error earlier, please help me. Thanks in advance!

Angular 1.5.x "angular.min.js:1 Uncaught SyntaxError: Unexpected token <" Error

I'm following the "MEAN Machine" book and I'm trying to set up a Angular with Express but I keep running into this error when I'm calling Angular.min.js:
"Uncaught SyntaxError: Unexpected token <"
I've been searching around for an hour or so now and haven't been able to fix it.
Folder Structure
Here's my Express Code:
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
morgan = require('morgan'),
cors = require('cors'),
path = require('path'),
config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(morgan('dev'));
app.use(express.static(__dirname + '/public'));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/index.html'));
});
app.listen(config.devPort);
console.log('Running on ' + config.devPort);
And here's where my index.html where Angular is being called:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Homepage</title>
<base href="/">
</head>
<body ng-app="sample">
<h1>Welcome to the homepage!</h1>
<div ng-controller="ScheduleCtrl as schedule">
<h1 ng-bind="schedule.test"></h1>
</div>
<!-- inject:js -->
<script src="/public/assets/lib/angular/angular.min.js"></script>
<script src="/public/app/app.js"></script>
<script src="/public/app/modules/schedule/schedule.controller.js"></script>
<!-- endinject -->
</body>
</html>
Here's the app.js file:
(function() {
'use strict';
angular
.module('sample', []);
})();
Here's the schedule.controller.js file:
(function() {
'use strict';
angular
.module('sample'),
.controller('ScheduleCtrl', ScheduleCtrl);
ScheduleCtrl.$inject = [];
function ScheduleCtrl() {
var vm = this;
vm.test = "Hello World!";
};
})();
EDIT:
I checked my console and the paths for the files are giving me a 304:
GET / 304 1.934 ms - -
GET /public/assets/lib/angular/angular.min.js 304 2.262 ms - -
GET /public/app/app.js 304 2.578 ms - -
GET /public/app/modules/schedule/schedule.controller.js 304 2.855 ms - -
Try to put the scripts in head tag instead of body tag (or before body tag), you're using AngularJS syntax (ng-app, etc.) before the script is included
This could be the error:
angular
.module('sample'), <-- this comma should not be here
.controller('ScheduleCtrl', ScheduleCtrl);

Catch all routes loading blank page Angular NodeJs

I was working on Angular app with routing (NodeJs as backend). Routing through pages works fine but when I try to reload page it gives 'cannot load path /home'. I browsed through and got to few solutions like THIS.
My code is
app.get('*', function (req, res) {
res.sendFile('mypath/index.html');
});
But this loads up blank page. Is there any way I can solve this issue?
This us how my server.js looks like
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var port = process.env.PORT || 8080; // set our port
var staticdir = process.env.NODE_ENV === 'production' ? 'dist.prod' : 'dist.dev'; // get static files dir
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
//app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
//app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/' + staticdir)); // set the static files location /public/img will be /img for users
// routes ==================================================
app.set('views', __dirname + '/app');
app.set('view engine', 'html');
require('./devServer/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Starting sever on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
app.get('/', function (req, res) {
res.render('index', {
page: 'index'
}
});
then out this into your config,
app.set('views', 'directory where index.html is');

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])
});

Express Pass Variable to Angular Without Templating Engine

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.

Resources