Node.js + Angular.js
Blogs20132013-10-22
Node.js + Angular.js
Here is a youtube vedio: Let’s Get CRUDdy: AngularJS and Node.js Ferrari Example, the source is at: https://github.com/jprichardson/talks-ncc3-demo. It is cool, using a way to render index.html as default:
var clientDir = path.join(__dirname, 'client');
app.get('/', function(req, res) {
res.sendfile(path.join(clientDir, 'index.html'))
})The client/index.html is called when first-time the app is loading. It is basically like Apache’s dir_module -> DirectoryIndex (DirectoryIndex: sets the file that Apache will serve if a directory is requested). The following is some of my summary:
1. The structure:
- client — css — js // app.js, controllers.js — partials //templates: list.html,details.html,form.html — vendor //libs: angular.js, bootstrap — index.html
- node_modules/
- resources/ //data.json
- server/ // api/cars.js
- test/
- .gitignore
- README.json
- server.js
2. Modules used:
$ npm init //generate package.json
$ npm install -g supervisor
$ supervisor -e 'html|js' node server
//Server side:
express.js, underscore,
mocha.js, jasimin.js //testing
fs-extra, reload
//Client side:
angularjs, bootstrap3. server.js:
var cars = require('./server/api/cars');
app.get('/', res.sendfile(path.join(clientDir, 'index.html');
app.get(/api/cars, cars.list);
app.get(/api/cars/total, cars.total);
app.get(/api/cars/:id, cars.read);
app.post(/api/cars/, cars.create);
app.put(/api/cars/:id, cars.update);
app.del(/api/cars/:id, cars.del);4. cars.js:
var _ = require('underscore'),
path=require('path'), fs=require('fs-extra');
module.exports.list = list;
module.exports.total = total;
module.exports.create = create;
module.exports.update = update;
module.exports.del = del;
function list(req, res) {
var offset = ~~req.query.offset || 0
, limit = ~~req.query.limit || 25
res.json(DATA.slice(offset*limit, offset*limit + limit))
}; ......