javascript - 使用 MEAN Stack - 查询 MongoDB 并将值作为变量传递

标签 javascript angularjs node.js mongodb mean

我正在使用 MEAN 堆栈来创建一个 Web 应用程序。我有我的 server.js、console.js、一个名为“contactlist”的 MongoDB,以及一个包含用于树形图的 Javascript 的 index.html。我想做的是查询我的 MongoDB 中的一个键,然后返回它的值(或者实际上只是获取任何信息)。然后我想将该值保存为变量并将其传递给我的index.html 中包含的javascript。

这是我重建教程代码最接近的一次。使用 mongojs 作为我的驱动程序,我的 server.js 中有这个:

app.get('/contactlist', function (req, res) {
console.log("I received a GET request")

db.contactlist.find({email:"bob11@email.com"},function(err, docs) {
//looks at the contact list database for anything with the email of bob11@email.com
    console.log(docs);
    res.json(docs);
});
});

在我的 Controller 中:

var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");

var refresh = function() {
$http.get('/contactlist').success(function(response) {
    console.log("I got the data I requested");
    $scope.contactlist = response;
    $scope.contact = "";
});
};

下面的 ng-repeat 函数的使用是原始应用程序使用的产物(显示所有联系人的列表)。现在我只想要一个值,但我不知道该使用什么函数。这是我的index.html:

<div class="container" ng-controller="AppCtrl">
    <table class="table">
        <thead>
            <tr>
        </thead>
        <tbody>
            <tr ng-repeat="contact in contactlist">
                <td>{{contact.name}}</td>
                <!-- grabs the name from parameters set out in server.js -->
            </tr>
        </tbody>
    </table>
</div>

这会在网页上显示我过滤的电子邮件 (bob11@email.com) 的名称 (“Bob”)。此时,即使只是能够将该名称保存为变量并将其传递给 javascript 也会有所帮助。 NG-repeat 绝对不是我想要使用的,但我对编程和 MEAN 堆栈很陌生,所以我有点卡住了。

谢谢。

最佳答案

我不太清楚你在问什么,但我会尽力提供帮助。

如果您询问如何在客户端上编辑 contact.name 变量,您可能应该熟悉 Angular's two way data binding 。这意味着 Controller 中对 $scope 的任何更改都会影响 HTML 中显示的数据,并且对 html 中变量的任何更改都将应用于 $scope。

例如,如果您想要编辑页面上的 contact.name,您可以使用绑定(bind)到 contact.name 的输入文本字段作为其模型。为此,我们需要 ng-model 在输入字段和我们想要更改的值之间建立桥梁。可能看起来像这样

  <ul>
    <li ng-repeat="contact in contactlist">
      Name: <input type="text" ng-model="contact.name"/>
    </li>
  </ul>

然后,我们可以向输入添加一个 ng-change 属性,以对更改执行操作。 See working demo here

关于javascript - 使用 MEAN Stack - 查询 MongoDB 并将值作为变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435005/

相关文章:

javascript - 使用 jQuery 通过 .eq() 选择多个元素

javascript - AngularJS 动画回调,等待下一个动画开始

AngularJS $http.get 返回速度不够快

javascript - AngularJS:按数字范围重复和过滤

javascript - _.map 返回时覆盖值

node.js - Web3.js sendSignedTransaction 给出 "Error: Failed to check for transaction receipt"

javascript - 使用 AJAX post 更改数据属性标签后 CSS 未更​​改

javascript - Instagram Stories API 中的 'user' 是谁

javascript - 不等待函数的异步方法 - VUE

javascript - nodejs post方法中的第二个参数是什么