更新版本(自定义指令 ngGoogleSuggest)
指令执行得更好,因为 onkeyup
执行http
对GoogleSuggest API的调用
elem.bind('keyup', scope.search);
标记:
<div data-ng-google-suggest ng-model="Search"></div>
注意:ngGoogleSuggest
我计划在经过更多测试后创建一个 GitHub 存储库
屏幕截图
调用 Google 搜索 API
- 终点:
'http://suggestqueries.google.com/complete/search
- 对于 JSON 响应(不是 XML),添加参数
&client=firefox
- Uri 编码搜索参数
- 通过添加使用JSONP协议
?callback=JSON_CALLBACK
来避免Access-Control-Allow-Origin 错误
示例$http
调用
scope.search = function() {
// If searchText empty, don't search
if (scope.searchText == null || scope.searchText.length < 1)
return;
var url = 'http://suggestqueries.google.com/complete/search?';
url += 'callback=JSON_CALLBACK&client=firefox&hl=en&q='
url += encodeURIComponent(scope.searchText);
$http.defaults.useXDomain = true;
$http({
url: url,
method: 'JSONP',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).
success(function(data, status, headers, config) {
// Api returns [ Original Keyword, Searches[] ]
var results = data[1];
if (results.indexOf(scope.searchText) === -1) {
data.unshift(scope.searchText);
}
scope.suggestions = results;
scope.selectedIndex = -1;
}).
error(function(data, status, headers, config) {
console.log('fail');
// called asynchronously if an error occurs
// or server returns response with an error status.
});