1

hey guys ,
I'm looking into Autocomplete field in Angularjs which fetches data from mongoose ... something like this https://stackoverflow.com/questions/18460374/angularjs-autocomplete-from-http but the thing is i dint understand properly... if u guys help me with simple examples it will be sooo glad!!!!

Thanks in advance!!!

Community
  • 1
  • 1
swati kiran
  • 675
  • 1
  • 4
  • 22

1 Answers1

1
$(function () {

  $("#search-query").autocomplete({<br>
      source: function (request, response) {<br>
         $.ajax({<br>
            url: "/search_member",<br>
            type: "GET",<br>
            data: request,  // request is the value of search input<br>
            success: function (data) {<br>
              // Map response values to fiedl label and value<br>
               response($.map(data, function (el) {<br>
                  return {<br>
                     label: el.fullname,<br>
                     value: el._id<br>
                  };<br>
                  }));<br>
               }<br>
            });<br>
         },
         <br>
         minLength: 3,

   <br>
         focus: function (event, ui) {<br>
            this.value = ui.item.label;<br>
            // Prevent other event from not being execute<br>
            event.preventDefault();<br>
         },<br>
         select: function (event, ui) {<br>
            // Prevent value from being put in the input:<br>
            this.value = ui.item.label;<br>
            // Set the id to the next input hidden field<br>
            $(this).next("input").val(ui.item.value);<br>
            // Prevent other event from not being execute     <br>       
            event.preventDefault();<br>
            // optionnal: submit the form after field has been filled up<br>
            $('#quicksearch').submit();<br>
         }<br>
  });<br>

});<br>

Servser-Side Coding

<br>
User = mongoose.model('User'); // Declare a new mongoose User
<br>
app.get('/search_member', function(req, res) {<br>
   var regex = new RegExp(req.query["term"], 'i');<br>
   var query = User.find({fullname: regex}, { 'fullname': 1 <br>}).sort({"updated_at":-1}).sort({"created_at":-1}).limit(20);<br>

  // Execute query in a callback and return users list<br>
  query.exec(function(err, users) {<br>
      if (!err) {<br>
         // Method to construct the json result set<br>
         var result = buildResultSet(users);<br>
         res.send(result, {<br>
            'Content-Type': 'application/json'<br>
         }, 200);<br>
      } else {<br>
         res.send(JSON.stringify(err), {<br>
            'Content-Type': 'application/json'<br>
         }, 404);<br>
      }<br>
   });<br>
});<br>
Paritosh
  • 11,144
  • 5
  • 56
  • 74
Jay Patel
  • 21
  • 3