如何使用Express 4 + Pug / Jade + Angularjs渲染数据

时间:2016-06-08 06:33:29

标签: angularjs node.js express pug mean-stack

我开始学习Express和Angularjs。在项目中,我想在服务器端呈现HTML并通过Angularjs绑定数据,但它不起作用。我在浏览器中看到ng-repeat被禁用

<body ng-app="photoApp" class="ng-scope">
  <h1>Express</h1>
  <p>Welcome to Express</p>
  <!-- ngView: -->
  <div ng-view="" class="ng-scope">
    <div id="photos" class="ng-scope">
      <!-- ngRepeat: photo in vm.photos -->
    </div>
  </div>
</body>

,因此没有显示数据。请帮我解决这个问题,谢谢先进!

项目结构

photo
--public
----javascript
------lib
------photoApp.js
--routes
----index.js
----photo.js
--views
----partials
------photo-list.pug
----error.pug
----index.pug
----layout.pug
--app.js

服务器端代码:

app.js

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');

var routes = require('./routes/index');
var users = require('./routes/users');
var photos = require('./routes/photos');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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('/', routes);
app.use('/users', users);
app.use('/photos', photos);

// 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 handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/partials/:name', function(req, res, next){
    var name = req.params.name;
    res.render('partials/' + name);
});

module.exports = router;

photos.js

var express = require('express');
var router = express.Router();

var photos = [];
photos.push({
  name: 'Node.js Logo',
  path: 'http://nodejs.org/images/logos/nodejs-green.png'
});
photos.push({
  name: 'Ryan Speaking',
  path: 'http://nodejs.org/images/ryan-speaker.jpg'
});

router.get('/api/get-all', function(req, res) {
    res.json(photos);
});

router.get('/', function(req, res) {
    res.render('photos');
});

module.exports = router;

layout.pug

doctype html
html
    head
        title= title
        link(rel='stylesheet', href='/stylesheets/style.css')
        script(src='javascripts/lib/angular.js')
        script(src='javascripts/lib/angular-route.js')
        script(src='javascripts/photoApp.js')
    body(ng-app="photoApp")
        block content

index.pug

extends layout

block content
  h1= title
  p Welcome to #{title}
  div(ng-view)

光list.pug

#photos
    .photos(ng-repeat="photo in vm.photos")
        h2 {{photo.name}}
        img(src="{{photo.path}}")

客户端代码:

photoApp.js

var photoApp = angular.module('photoApp', ['ngRoute']);
photoApp.controller('PhotoListController', PhotoListController);
photoApp.config(['$routeProvider', function($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl: 'partials/photo-list',
            controller: 'PhotoListController',
            controllerAs: 'vm'
        })
        .otherwise({
            redirectTo: '/'
        });
}]);

function PhotoListController($scope, $http) {
    var vm = this;
    vm.getAllPhotos = getAllPhotos; 

    function getAllPhotos(){
        $http.get('/photos/api/get-all')
            .success(function(response) { vm.photos = response.photos; })
            .error(function() { console.log('Error when getting all photos'); });
    }
}

0 个答案:

没有答案