Angularjs 提前输入搜索功能
所以我使用的是typeahead指令,它是AngularUI项目的一部分。我有一个调用工厂的函数(使用$resource调用api)。第一个功能不起作用,但第二个功能起作用。这里发生了什么不同的事情?我认为这些会产生完全相同的结果,但显然我错了:Angularjs 提前输入搜索功能,angularjs,typeahead,Angularjs,Typeahead,所以我使用的是typeahead指令,它是AngularUI项目的一部分。我有一个调用工厂的函数(使用$resource调用api)。第一个功能不起作用,但第二个功能起作用。这里发生了什么不同的事情?我认为这些会产生完全相同的结果,但显然我错了: // this didn't work, it doesn't display a list of items in typeahead, no errors. $scope.getLocation = function(val) {
// this didn't work, it doesn't display a list of items in typeahead, no errors.
$scope.getLocation = function(val) {
return LocationService.search({ term: val }, function (res) {
return res.data.map(function (item) {
return item;
});
});
};
// this worked
$scope.getLocation = function(val) {
return LocationService.search({ term: val }).$promise.then(function (res){
return res.data.map(function (item) {
return item;
});
});
};
您是否将
$resource
包装在LocationService
中?比如:
function LocationService($resource) {
return {
search : function(query){
var locationResource = $resource('url/',
{},
{
search : {
method: 'POST',
responseType : 'json'
}
});
return locationResource.search({ q : query });
}
};
}
如果是这样,在第一个示例中,您只是将回调作为第二个变量传递给LocationService
,函数定义中没有处理该变量。$resource
的返回函数可以将回调作为第二个参数,但如果您包装了回调,则不能。如果需要,可以将回调传递给服务本身,如:
function LocationService($resource) {
return {
search : function(query, cb){
var locationResource = $resource('url/',
{},
{
search : {
method: 'POST',
responseType : 'json'
}
});
return locationResource.search({ q : query }, cb);
}
};
}