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

Using MEAN Stack - Querying MongoDB and Passing Value as a Variable

本文关键字:变量 堆栈 MEAN 查询 MongoDB 使用      更新时间:2023-09-26

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

这是我重建教程代码的最接近的一次。使用mongojs作为我的驱动程序,我的服务器.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);
});
});

在我的控制器中:

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>

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

谢谢。

我不完全确定你在问什么,但我会尽力帮你的。

如果您询问如何在客户端上编辑contact.name变量,您可能应该熟悉Angular的双向数据绑定。这意味着,对控制器中$scope的任何更改都将影响HTML中显示的数据,对HTML中变量的任何更改将应用于$scope。

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

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

然后,我们可以将ng-change属性添加到输入中,以对更改执行操作。请参阅此处的工作演示

第一个解决方案:您可以在html页面和绑定机制中使用ng-init-for,类似于

<div ng-init="param='value';">
    <div ng-controller="yourController" >
        <label>param: {{value}}</label>
    </div>
</div>

现在,无论你在html文件中使用什么参数,都可以用于你的控制器功能

function yourController($scope) {
        console.log($scope.param);
}

第二种解决方案:你可以制作一个服务来传递控制器中的值,类似于这个

var app = angular.module('myApp', []);
app.factory('valuepassing', function() {
    var myvaluepassingService = {};
         data =[];
    myvaluepassingService.addvalue = function(value) {
        data.push(value);
    };
    myvaluepassingService.removevalue = function(value) {
        var index = data.indexOf(value);
        data.splice(index, 1);
    };
    myvaluepassingService.data = function() {
        return data;
    };
    return myvaluepassingService;
});
function MyCtrl($scope, valuepassing) {
    $scope.newvalue = {};
    $scope.valuepassing = valuepassing;    
}