用 Angular 发帖到 Mongo

Posting with Angular to Mongo

我的设置是 NodeJS、MongoDB 和 Angular。我目前正在尝试将 POSTing 功能添加到我的测试代码中,但我无法完全理解它。目前,我可以从数据库中提取数据,并且我根据我见过的一些示例拼凑了一个快速而肮脏的 form/factory 来尝试使 POST 函数正常工作。

我 运行 遇到的问题实际上是获取要添加到数据库的值。当我提交表单时,会在数据库中创建一个新的 ObjectID,其中包含“_v”字段且值为 0。所以我知道 POST 至少被发送到数据库,但我想要的值是不是。我确定我在做一些愚蠢的事情,非常感谢任何帮助。

这是我的 controller/factory 设置:(我将 POST 工厂命名为 "taco" 所以它会很显眼。也因为他们'很好吃。)

      angular.module('app', ['ngRoute'])
     .factory('Users', ['$http', function($http) {
        return $http.get('/users');
     }])
    .factory('taco', ['$http', function($http) {
        return $http.post('/users');
     }])
     .controller('UserController', ['$scope', 'Users', function($scope, Users) {
        Users.success(function(data) {
            $scope.users = data;
        }).error(function(data, error) {
            console.log(error);
            $scope.users = [];
        });
     }])
     .controller('ExampleController', ['$scope', 'taco', function($scope, taco) {
     $scope.submit = function() {
      if ($scope.users.name) {
      $scope.name.post(this.name);
      $scope.name = '';
    }
  };
}]);

这是我的表格:

<div>
   <form ng-submit="submit()" ng-controller="ExampleController">
      Enter the things:<br/>
      <input type="text" ng-model="name" name="user.name" placeholder="name" /><br/>
      <input type="text" ng-model="emp_id" name="user.emp_id" placeholder="EID" /><br/>
      <input type="text" ng-model="loc" name="user.loc" placeholder="location" /><br/>
      <input type="submit" id="submit" value="Submit" />
   </form>
</div>

post 使用 $http 服务,您可以:

angular.module('myApp')

.controller('MyController', function($scope, $http) {
  $http.post('/destination', {my: 'data'});
});

您没有在 POST 请求中发送任何数据。 taco 服务仅执行 $http.post 调用和 returns 承诺。

请查看$http服务文档:https://docs.angularjs.org/api/ng/service/$http

我会定义一个函数提交,一旦用户点击提交就会发送数据:

$scope.submit = function() {
  $http.post('/destination', {my: 'data'});
}