我试图在Angular指令中实现
jquery的自动完成.我收到的数据源自websocket响应.这不行,我认为响应延迟是造成这个问题的.
如果有人可以对下面的代码进行阐述,我会感激一下.有什么优雅的技术来实现这种使用某种请求/响应或承诺吗?
app.directive('autoComplete',function($rootScope,locationAutoCompleteService,$timeout,$http,programLocationModel ) {
return {
restrict: 'A',scope: {
serviceType: '@serviceType'
},link: function(scope,elem,attr,ctrl) {
var autoItem = [];
scope.change = function () {
locationAutoCompleteService.unSubscribe();
var service = locationAutoCompleteService.getServiceDeFinition();
service.filters.pattern = scope.inputVal;
locationAutoCompleteService.subscribe();
};
scope.$on('myData',function(event,message){
if ( message !== null && message.results !== null) {
autoItem = [];
for ( var i = 0; i < message.results.length; i++) {
autoItem.push({ label: message.results[i].name,id: message.results[i].id });
}
}
});
elem.autocomplete({
source: autoItem,select: function( event,ui ) {
$timeout(function() {
elem.trigger('input');
},0);
}
});
}
};
});
解决方法
你可以随时利用这些人所做的工作:
http://angular-ui.github.io/bootstrap
– 向下滚动到头脑 –
这是一个Plunkr:http://plnkr.co/edit/9zsrvLLfH8hKGwmIeZVv?p=preview
这里有一些标记:
HTML
<div class='container-fluid' ng-controller="TypeaheadCtrl">
<pre>Model: {{selected| json}}</pre>
<input type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue">
</div>
JS
function TypeaheadCtrl($scope) {
$scope.selected = undefined;
$scope.states = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','north Dakota','north Carolina','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
}
更新
看来我正在关注错误的问题.尝试在$on处理程序中移动自动完成调用.
喜欢这个:
app.directive('autoComplete',programLocationModel) {
return {
restrict: 'A',scope: {
serviceType: '@serviceType'
},ctrl) {
var autoItem = [];
scope.change = function() {
locationAutoCompleteService.unSubscribe();
var service = locationAutoCompleteService.getServiceDeFinition();
service.filters.pattern = scope.inputVal;
locationAutoCompleteService.subscribe();
};
scope.$on('myData',message) {
if (message !== null && message.results !== null) {
autoItem = [];
for (var i = 0; i < message.results.length; i++) {
autoItem.push({
label: message.results[i].name,id: message.results[i].id
});
}
elem.autocomplete({
source: autoItem,select: function(event,ui) {
$timeout(function() {
elem.trigger('input');
},0);
}
});
}
});
}
};
});