The app structure:
Front-end: app.js
/** * Created by Answer1215 on 12/9/2014. */'use strict';function MainCtrl(PeopleService) { var vm = this; vm.people = []; vm.selectedPerson = {}; vm.getPeople = PeopleService.getPeople().then(function(response) { vm.people = response.data; }); vm.selectPerson = function(person) { PeopleService.getSelectedPerson(person).then(function(response) { vm.selectedPerson = response.data; vm.selectedPerson.fullName = response.data.firstName + " " + response.data.lastName; }); }}function PeopleService($http) { var PeopleService = {}; PeopleService.getPeople = function() { return $http.get('http://localhost:3000/people'); } PeopleService.getSelectedPerson = function(person) { return $http.get('http://localhost:3000/people/'+person._id); } return PeopleService;}angular.module('app',[ 'ngResource']) .controller('MainCtrl', MainCtrl) .service('PeopleService', PeopleService);
- { {person.firstName}}
{ {vm.selectedPerson.fullName}}
{ {vm.selectedPerson.email}}
Backend:
server.js
'use strict';var express = require('express');var cors = require("cors");var app = express();app.use(cors());var people = require('./controller/people');app.get('/people', people.getAll);app.get('/people/:id', people.get);app.listen(3000);
controller/people.js
/** * Created by Answer1215 on 12/26/2014. */var model = require('../model/people');exports.getAll = function(request, response){ model.getAll(function(err, data) { if(err) response.json(503, {error: true}); response.json(200, data); });}exports.get = function(request, response){ var id = request.params.id; model.get(id, function(err, data) { if(err) response.json(503, {error: true}); response.json(200, data); });}
model/people.js
/** * Created by Answer1215 on 12/26/2014. */var mongoose = require('../lib/mogoose');var personSchema = { firstName:String, lastName:String, email:String};//create a person model, and rename db as peoplevar Person = mongoose.model('Person', personSchema);exports.getAll = function(callback) { Person.find().select("firstName").exec(function(err, data) { // response.json(200, data); callback(err, data); });}exports.get = function(id, callback){ Person.findById(id, function(err, data) { //response.send(data); callback(err, data); });}
lib/mogoose.js
/** * Created by Answer1215 on 12/26/2014. */var mongoose = require('mongoose');mongoose.connect('mongodb://localhost/simple');module.exports = mongoose;