Angular.js:无法使用ng-repeat和handle-bars在视图中显示用户属性

时间:2017-04-05 23:44:52

标签: javascript angularjs node.js postgresql

Angular.js,Node.js,Postgresql

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 pathfinderUI = require('pathfinder-ui');
var engines = require('consolidate');

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

var app = express();

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

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

// pathfinder
app.use('/pathfinder', function(req, res, next){
    pathfinderUI(app)
    next()
}, pathfinderUI.router)

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

public / javascripts / user.js:

var app = angular.module('sendgrid-webhook', [])
app.controller('mainController', ($scope, $http) => {
  $scope.formData = {};
  // Get all users
  $http.get('api/v1/users')
    .then(function(response) {
      $scope.userData = response.data;
      console.log(response.data);
    });
    // Create a new todo
  $scope.createUser = () => {
    $http.post('/api/v1/users', $scope.formData)
    .success((data) => {
      $scope.formData = {};
      $scope.userData = data;
      console.log(data);
    })
    .error((error) => {
      console.log('Error: ' + error);
    });
  };
  // Delete a todo
  $scope.deleteUser = (userID) => {
    $http.delete('/api/v1/users/' + todoID)
    .success((data) => {
      $scope.userData = data;
      console.log(data);
    })
    .error((data) => {
      console.log('Error: ' + data);
    });
  };
});

的index.html:

<!DOCTYPE html>
<html ng-app="sendgrid-webhook">
  <head>
    <title>SendGrid JS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <script src="//code.jquery.com/jquery-2.2.4.min.js" type="text/javascript"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
    <script src="javascripts/app.js"></script>
  </head>
  <body ng-controller="mainController">
    <div class="container">
      <form>
        <div class="form-group">
          <input type="text" class="form-control input-lg" placeholder="Username" ng-model="formData.username">
          <input type="text" class="form-control input-lg" placeholder="Email Address" ng-model="formData.email">
          <input type="text" class="form-control input-lg" placeholder="Password" ng-model="formData.password">
        </div>
        <button type="submit" class="btn btn-primary btn-lg" ng-click="createUser()">Create User</button>
      </form>
      <div class="user-list">
        <ul>
          <li ng-repeat="user in userData"><input type="checkbox" ng-click="deleteUser(user.id)">
            {{ user.username }}
          </li>
        </ul>
      </div>
    </div>
  </body>
</html>

JSON响应:

[{"id":1,"username":"test","email":"test@test.com","password":"newpass"},{"id":4,"username":"First","email":"first@gmail.com","password":"test"},{"id":5,"username":"Tesing a third user","email":"newemail@gmail.com","password":"testing"}]

控制台日志对象:

userData Object in Console

在app.js的第6行,我正在对用户端点进行API调用,返回正确的用户对象数组。它保存为'$ scope.userData'。当我是一个检查返回值的调试器时,我得到一个包含三个用户的数组。如果查看index.html,可以看到为每个复选框创建的复选框。

在index.html的第24行,我在userData“'中使用'ng-repeat =”user设置'li'元素。在每个'li'元素中,我希望用{{user.username}}显示用户的属性。

我的观点是迭代用户对象数组,并为每个用户对象创建'li',但为什么把手不显示我要求的user.username属性?

编辑:

It works in Plunker when I replace the AJAX call with the response data from the console

但是dir结构也不同,并且不涉及节点。

1 个答案:

答案 0 :(得分:0)

我弄清楚问题是什么。

app.use(express.static(path.join(__dirname, 'public')));

我正在为/views文件夹提供视图服务。现在,html正好被提供给浏览器,但是,由于express使用Angular(?)提供静态资源的方式,我需要将index.html视图移动到文件树中的公共文件夹中。拖放,{{ }}符号工作正常。

感谢任何人的帮助。如果您想澄清一下,请告诉我!

PS:发布一切,甚至你的Q&amp; A上的Dir Struct,它可能会帮助我。