我很难让uib-typeahead工作,因为我需要它。
请参阅:https://jsfiddle.net/0wp1t0ut/ - 如果在输入框中键入“g”,则“germany”会正确添加到源数组中,但是在下一次按键之前,typeahead视图不会更新。即德国在那里,但是在我按下“e”之前我无法选择它。
基本上我想要实现的是一种类型,它将在新结果进入时动态更新(而不是在我将数组返回到预先输入之前等待所有调用完成)。
[请注意,在我的实际代码中,typeahead上的ng-change是一个对不同来源进行多次调用的函数,我希望第一次调用返回数据后,typeahead会显示数据,并添加到因为后来的调用会返回更多结果。]
有没有人遇到过这个问题,或者能够提供任何建议(如果有更好的选择已经存在,很乐意使用不同的类型!)
HTML:
<div ng-app="myApp" ng-controller="MyCtrl as vm">
<label>TypeAhead:</label>
<input type="text" ng-model="selected" ng-change="vm.add()" uib-typeahead="state as state.descrizione for state in vm.states | filter:$viewValue | limitTo:8" typeahead-model-change class="form-control" >
<label>Model</label>
<pre>{{vm.states|json}}</pre>
<label>Modify Model Description:</label>
<input ng-model="selected.descrizione" class="form-control">
</div>
JS:
var myApp = angular.module('myApp', ['ui.bootstrap']);
myApp.controller('MyCtrl', [function() {
var vm = this;
vm.add = function(){
var a = {
codice: 'at',
descrizione: 'germany'};
vm.states.push(a)
}
vm.states = [{
codice: 'it',
descrizione: 'italia'
}, {
codice: 'fr',
descrizione: 'francia'
}];
}]);
myApp.directive('typeaheadModelChange', function() {
return {
require: ['ngModel', 'typeaheadModelChange'],
controller: ['$scope', '$element', '$attrs', '$transclude', 'uibTypeaheadParser', function($scope, $element, $attrs, $transclude, uibTypeaheadParser) {
var watchers = [];
var parserResult = uibTypeaheadParser.parse($attrs.uibTypeahead);
var removeWatchers = function() {
angular.forEach(watchers, function(value, key) {
value();
});
watchers.length = 0;
}
var addWatchers = function(modelCtrl) {
watchers.push($scope.$watch('selected', function(newValue, oldValue) {
if (oldValue === newValue)
return;
if (newValue) {
var locals = [];
locals[parserResult.itemName] = newValue;
$element.val(parserResult.viewMapper($scope, locals));
}
}, true));
}
this.init = function(modelCtrl) {
modelCtrl.$formatters.push(function(modelValue) {
removeWatchers();
addWatchers(modelCtrl);
return modelValue;
});
};
}],
link: function(originalScope, element, attrs, ctrls) {
ctrls[1].init(ctrls[0]);
}
};
});