我试图写一个自动完成指令,从服务器使用$ http请求(不使用任何外部插件或脚本)提取数据。目前它只适用于静态数据。现在,我知道我需要插入我的$ http请求到源指令,但我找不到任何有关的主题的好文档。
http请求
$http.post($scope.url,{ "command": "list category() names"}).
success(function(data,status) {
$scope.status = status;
$scope.names = data;
})
.
error(function(data,status) {
$scope.data = data || "Request Failed";
$scope.status = status;
});
指示
app.directive('autoComplete',function($timeout) {
return function(scope,iElement,iAttrs) {
iElement.autocomplete({
source: scope[iAttrs.uiItems],select: function() {
$timeout(function() {
iElement.trigger('input');
},0);
}
});
};
});
视图
<input auto-complete ui-items="names" ng-init="manualcat='no category entered'" ng-model="manualcat">
所以,我怎么把这一切正确的角度方式?
我做了一个自动完成指令,并将其上传到GitHub。它还应该能够处理来自HTTP请求的数据。
这里是演示:http://justgoscha.github.io/allmighty-autocomplete/
这里的文档和存储库:https://github.com/JustGoscha/allmighty-autocomplete
因此,基本上你必须返回一个承诺,当你想从HTTP请求中获取数据,当数据加载时得到解决。因此,您必须注入发出HTTP请求的$ qservice / directive / controller。
例:
function getMyHttpData(){
var deferred = $q.defer();
$http.jsonp(request).success(function(data){
// the promise gets resolved with the data from HTTP
deferred.resolve(data);
});
// return the promise
return deferred.promise;
}
我希望这有帮助。