嘿伙计,
我正在研究 Angularjs 中的自动填充字段,该字段从 mongoose 中获取数据......类似于此https://stackoverflow.com/questions/18460374/angularjs-autocomplete-from-http但事情是我正确地理解......如果你们用简单的例子帮助我,那就太棒了!!!!
提前致谢!!!
答案 0 :(得分: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>