Val Saven Val Saven - 2 months ago 37
Jade Question

Angular doesn't work with Express and Pug

I have no idea why, but I can't force Angular working here. Does anybody have ideas of why this may be?
I can't even make a simple input form with binded model. There are always just {{model}} and this

enter image description here

File tree

enter image description here

/app.js

var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');


app.use(express.static(__dirname + '/client'));
app.use(bodyParser.json());
require('./app/routes.js')(app);

app.listen(port, () => {
console.log('Server listening on port 3000...');
});


/app/routes.js

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./db/mes.db');
var _ = require('underscore');


module.exports = function (app) {
app.get('/messages', (req, res, next) => {
try {
var messages = [];

// Some db stuff

res.json(messages);
} catch (err) {
next(err);
}
});

app.set('views', './views');
app.set('view engine', 'pug');

app.get('*', (req, res) => {
res.render('index');
});
};


/client/controller.js

angular.module('myViewerController', [])
.controller('mainController', ['$scope','$http','Messages', function($scope, $http, Messages) {
$scope.formData = {};
$scope.loading = true;

Messages.get()
.success(function(data) {
$scope.messages = data;
$scope.loading = false;
})
.error(data => {
console.log('Error: ' + data);
});
}]);


/client/core.js

angular.module('myViewer', ['myViewerController', 'myViewerService']);


/client/service.js

angular.module('myViewerService', [])
.factory('Messages', ['$http', function ($http) {
return {
get: function () {
return $http.get('/messages');
}
}
}]);


/views/layout.pug

doctype html
html(ng-app='myViewer')
head
meta(charset='utf-8')
link(href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css', rel='stylesheet')
body(ng-controller='mainController')
block content
block scripts
script(src='http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js')
script(src='../client/controller.js')
script(src='../client/service.js')
script(src='../client/core.js')


/views/index.pug

extends layout

block content
.container(ng-controller='mainController')
.row
table.table-bordered
thead
tr
th Id
th Caller
th Message
th Date
tbody(ng-repeat='m in messages')
tr
td {{m.id}}
td {{m.caller}}
td {{m.text}}
td {{m.date}}

Answer

Thanks Muli Yulzary. I've just changed

in /app/routes.js

var path = require('path');

// .. 

app.get('/', (req, res) => {
    res.render('index', {root: path.join(__dirname, '../client')});
  });

and in /views/layout.pug

script(src='./controller.js')
script(src='./service.js')
script(src='./core.js')
Comments