在ToDo列表应用程序中设置更新

时间:2013-11-22 13:58:37

标签: javascript node.js angularjs express

我正在使用AngularJS,Node,Express和MongoDB创建一个CRUD todo应用程序。除了更新部分,我已经找到了所有部件。我不确定如何实现它或代码可能是什么样子。特别是AngularJS的东西(快速路由并不是那么糟糕)。如果我可以通过ID更新,我会喜欢它。希望得到一些投入。

function mainController($scope, $http) {
    $scope.formData = {};

// when landing on the page, get all todos and show them
$http.get('/api/todos')
    .success(function(data) {
        $scope.todos = data;
    })
    .error(function(data) {
        console.log('Error: ' + data);
    });

// when submitting the add form, send the text to the node API
$scope.createTodo = function() {
    $http.post('/api/todos', $scope.formData)
        .success(function(data) {
            $('input').val('');
            $scope.todos = data;
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
};

// delete a todo after checking it
$scope.deleteTodo = function(id) {
    $http.delete('/api/todos/' + id)
        .success(function(data) {
            $scope.todos = data;
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });
};

以下是重要的路线。

app.get('/api/todos', function(req, res) {
    // use mongoose to get all todos in the database
    Todo.find(function(err, todos) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err)
            res.send(err)

        res.json(todos); // return all todos in JSON format
    });
});

// create todo and send back all todos after creation
app.post('/api/todos', function(req, res) {

    // create a todo, information comes from AJAX request from Angular
    Todo.create({
        text : req.body.text,
        done : false
    }, function(err, todo) {
        if (err)
            res.send(err);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });

});

// delete a todo
app.delete('/api/todos/:todo_id', function(req, res) {
    Todo.remove({
        _id : req.params.todo_id
    }, function(err, todo) {
        if (err)
            res.send(err);

        // get and return all the todos after you create another
        Todo.find(function(err, todos) {
            if (err)
                res.send(err)
            res.json(todos);
        });
    });
});




// application -------------------------------------------------------------
app.get('*', function(req, res) {
    res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};

1 个答案:

答案 0 :(得分:2)

有两种方法 - 你可以使用$ http.put bu你也可以使用$ resource。我希望这会对你有所帮助

<强>的index.html

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-resource.min.js"></script>
  <script type="text/javascript" src="angularjs_app.js"></script>
</head>

<body>
  <div ng-controller="MainController">
    <form name="todoForm" novalidate>
      <label>Id</label>
      <input type="text" name="_id" ng-model="editTodo._id">
      <br/>    
      <label>Subject</label>
      <input type="text" name="subject" ng-model="editTodo.subject">
      <br/>
      <label>Description</label>
      <input type="text" name="desc" ng-model="editTodo.desc">
      <br/>
      <button ng-click="updateTodo()">Update Todo</button>
    </form>
  </div>
</body>

</html>

angularjs_app.js(1路)

var myApp = angular.module('myApp', []);

myApp.controller('MainController', ['$scope',
  function($scope) {

    $scope.updateTodo = function() {

      $http.put('/api/todos/' + $scope.editTodo._id, $scope.editTodo).success(function() { 
        alert('Todo updated');
      });

      // Or you can try
      // $http.put('/api/todos/' + $scope.editTodo._id, {"todo": $scope.editTodo})
      // .success(function(data, status, headers, config){
      //   $scope.editTodo = data.todo;
      // })
      // .error(function(data, status, headers, config){
      //   alert(data.error_message);
      // });

    };
}]);

angularjs_app.js(2路)

var myApp = angular.module('myApp', ['ngResource', 'myAppServices']);

myApp.controller('MainController', ['$scope', 'TodoFactory',
  function($scope, TodoFactory) {

    $scope.updateTodo = function() {
      TodoFactory.update($scope.editTodo, function() {
        alert('Todo updated');
      });
    };
}]);

var myAppServices = angular.module('myAppServices', ['ngResource']);

myAppServices.factory('TodoFactory', ['$resource',
  function($resource) {
    return $resource('/api/todos/:todoId', {}, {
       update: {method:'PUT', params: {todoId: '@_id'}}
    });
  }
]);

<强> nodejs_server.js

var express = require('express');
var path = require('path');
var http = require('http');
var todos = require('./routes_todos');

var app = express();

app.configure(function() {
  app.set('port', process.env.PORT || 3000);
  app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(path.join(__dirname, 'public')));
});

app.get('/api/todos', todos.findAll);
app.get('/api/todos/:id', todos.findById);
app.post('/api/todos', todos.add);
app.put('/api/todos/:id', todos.update);
app.delete('/api/todos/:id', todos.remove);

http.createServer(app).listen(app.get('port'), function() {
  console.log("Express server listening on port " + app.get('port'));
});

<强> routes_todos.js

var mongo = require('mongodb');

var Server = mongo.Server;
var Db = mongo.Db;
var BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('todosdb', server);

db.open(function(err, db) {
  if (!err) {
    console.log("Connected to 'todosdb' database");
    db.collection('todos', {strict: true}, function(err, collection) {
      if (err) {
        console.log("Error todos does not exist");
      }
    });
  }
});

exports.findAll = function(req, res) {
  db.collection('todos', function(err, collection) {
    collection.find().toArray(function(err, items) {
      console.log('todos send from DB');
      res.send(items);
    });
  });
};

exports.findById = function(req, res) {
  var id = req.params.id;
  console.log('Retrieving todo: ' + id);
  db.collection('todos', function(err, collection) {
    collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
      res.send(item);
    });
  });
};

exports.add = function(req, res) {
  var todo = req.body;
  console.log('Adding todo: ' + JSON.stringify(todo));
  db.collection('todos', function(err, collection) {
    collection.insert(todo, {safe: true}, function(err, result) {
      if (err) {
        res.send({'error': 'An error has occurred'});
      } else {
        console.log('Success: ' + JSON.stringify(result[0]));
        res.send(result[0]);
      }
    });
  });
};

exports.update = function(req, res) {
  var id = req.params.id;
  var todo = req.body;
  console.log('Updating todo: ' + id);
  console.log(JSON.stringify(todo));
  delete todo._id;
  db.collection('todos', function(err, collection) {
    collection.update({'_id': new BSON.ObjectID(id)}, todo, {safe: true}, function(err, result) {
      if (err) {
        console.log('Error updating todo: ' + err);
        res.send({'error': 'An error has occurred'});
      } else {
        console.log('' + result + ' document(s) updated');
        res.send(todo);
      }
    });
  });
};

exports.remove = function(req, res) {
  var id = req.params.id;
  console.log('Removing todo: ' + id);
  db.collection('todos', function(err, collection) {
    collection.remove({'_id': new BSON.ObjectID(id)}, {safe: true}, function(err, result) {
      if (err) {
        res.send({'error': 'An error has occurred - ' + err});
      } else {
        console.log('' + result + ' document(s) removed');
        res.send(req.body);
      }
    });
  });
};