如何保存角形数据?

时间:2015-12-29 05:51:18

标签: javascript angularjs node.js forms mongodb

我是MEAN堆栈的新手,所以我想尝试用它制作基本表单。我使用角度形式验证创建它,但我无法将其保存到mongodb。我的问题是,我不明白如何通过表单字段将内容提交到app.js。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js'></script>
</head>
<body ng-app="GenApp">
  <div ng-controller="FormController">
  <form name="form" class="registration-form" novalidate>
    Name:
    <input type="text" ng-model="user.name" name="uName" required="" />
    <br />
    <div ng-show="form.$submitted || form.uName.$touched">
      <div ng-show="form.uName.$error.required">Tell us your name.</div>
    </div>

    E-mail:
    <input type="email" ng-model="user.email" name="uEmail" required="" />
    <br />
    <div ng-show="form.$submitted || form.uEmail.$touched">
      <span ng-show="form.uEmail.$error.required">Input your email</span>
      <span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
    </div>
    <input type="button" ng-click="reset(form)" value="Reset" />
    <input type="submit" ng-click="update(user)" value="Save" />
  </form>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <script src="js/controller.js"></script>
  <script src="app.js"></script>
</div>
</body>
</html>

controller.js

var app = angular.module("GenApp", []);

app.controller('FormController', ['$scope', function($scope) {
  $scope.master = {};

  $scope.update = function(user) {
    $scope.master = angular.copy(user);

  };

  $scope.reset = function(form) {
    if (form) {
      form.$setPristine();
      form.$setUntouched();
    }
    $scope.user = angular.copy($scope.master);
  };

  $scope.reset();
}]);

app.js(服务器)

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var database_url = "mongodb://test:test@ds035965.mongolab.com:35965/addressbook";
var port = process.env.PORT || 8080;

mongoose.connect(database_url);

var Schema = mongoose.Schema;

var personSchema = new Schema({
    name: String,
    email: String
});

var Person = mongoose.model('Person', personSchema);

有谁知道我会如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:0)

尝试创建REST API,并通过POST请求提交用户数据

app.js (server)

app.post("/user/:name", function(req,res,next){
//persistence logic
});


controller.js

app.controller('FormController', ['$scope','$http', function($scope,$http) {
  $scope.master = {};

  $scope.update = function(user) {
    $scope.master = angular.copy(user);
   $http({
    method: 'POST',
    url: hostname:port + '/user/' + user.name
  }).then(function successCallback(response) {

  }, function errorCallback(response) {

  });

  };

  $scope.reset = function(form) {
    if (form) {
      form.$setPristine();
      form.$setUntouched();
    }
    $scope.user = angular.copy($scope.master);
  };

  $scope.reset();
}]);