2016-03-22 215 views
1

因此,我使用的是一个属于Angular UI项目的typeahead指令。我有一个调用工厂的函数(使用$ resource调用api)。第一个功能不起作用,但第二个功能没有。这里发生了什么不同?我认为这会产生完全相同的结果,但显然我错了:Typeahead搜索功能

// 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; 
     }); 
    }); 
}; 

回答

1

你有$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); 
    } 
}; 
} 
+0

哦!我现在明白了,谢谢! – TheWebGuy