简体   繁体   中英

Using Angular to pull data from MongoDB based on form input

I am new to Angular and Mongo, and am hoping to use Angular js to pull data from a Mongo database to populate a div on a single-page website I'm building. What data is pulled will depend on what option a user selects in a dropdown option on a form. There are a Lot of options out there for Angular, and I was hoping that someone with more experience with it could point me in the right direction. Below are the relevant bits of my code:

<body ng-app="">
  <div id='ad'> </div><!-- to be populated with data from MongoDB -->
<select id='climateZone' ng-model="zone" >
  <option value="z3">3</option>
  <option value="z4">4</option>
  <option value="z5">5</option>
  <option value="z6">6</option>
  <option value="z7">7</option>
  <option value="z8">8</option>
  <option value="z9">9</option>
  <option value="z10">10</option>
</select>
 <button id='Go'><h2>Go!</h2></button>

I want it so that when a user selects one of these options, and presses the 'go' button, the 'ad' div will be populated with option-specific information from the database.

I hope that's all clear; any help is appreciated!

As far as I know you can't make HTTP request directly to MongoDB. Instead you need a server-side implementation that communicates with the database for you. If you are using Node for the back-end you can take a look on Mongoose: http://mongoosejs.com/

Mongoose is one of the many libs for MongoDB, you define you models, make queries, post data, and so on. Let's say I want to get the data based on a parameter. At first you need a model for your data:

var Cat = mongoose.model('Cat', { name: String });

Then you can start operating on top of the DB connection. The example bellow should bring you all cats named "Toddy":

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDB');

Cat.find({name: 'Toddy'}, function (err, result) {
    if (err) return console.error(err);
    console.log(result);
});

That said, you can use the ngChange and ngModel directives to put the value of the combo on a variable and react properly when it changes, like so:

<select id='climateZone' ng-model="zone" ng-change="loadData()">
    <option value="z3">3</option>
    <option value="z4">4</option>
    <option value="z5">5</option>
    <option value="z6">6</option>
    <option value="z7">7</option>
    <option value="z8">8</option>
    <option value="z9">9</option>
    <option value="z10">10</option>
</select>

Being both "zone" and "loadData()" members of your $scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM