我在以下用例中遇到问题 提前输入 :
问题:
因此,故事的寓意是,在第一种情况下,如果未从列表中选择字符串并且它是列表字符串的子字符串,则应清除字符串...
那么,也许是一种预先搜索焦点设置?
HTML:
<input type="text" focus-me="opened" ng-focus="onFocus($event)" ng-show="opened" ng-trim="false" ng-model="selected" empty-typeahead typeahead="state for state in states | filter:$viewValue:stateComparator" class="form-control" />
JS:(function () {
var secretEmptyKey = '[$empty$]'
angular.module('plunker', ['ui.bootstrap'])
.directive('focusMe', function($timeout, $parse) {
return {
//scope: true, // optionally create a child scope
link: function(scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function(value) {
if(value === true) {
$timeout(function() {
element[0].focus();
});
}
});
}
};
})
.directive('emptyTypeahead', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
// this parser run before typeahead's parser
modelCtrl.$parsers.unshift(function (inputValue) {
var value = (inputValue ? inputValue : secretEmptyKey); // replace empty string with secretEmptyKey to bypass typeahead-min-length check
modelCtrl.$viewValue = value; // this $viewValue must match the inputValue pass to typehead directive
return value;
});
// this parser run after typeahead's parser
modelCtrl.$parsers.push(function (inputValue) {
return inputValue === secretEmptyKey ? '' : inputValue; // set the secretEmptyKey back to empty string
});
}
}
})
.controller('TypeaheadCtrl', function($scope, $http, $timeout) {
$scope.selected = undefined;
$scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Wyoming'];
$scope.opened = true;
$scope.stateComparator = function (state, viewValue) {
return viewValue === secretEmptyKey || (''+state).toLowerCase().indexOf((''+viewValue).toLowerCase()) > -1;
};
$scope.onFocus = function (e) {
$timeout(function () {
$(e.target).trigger('input');
$(e.target).trigger('change'); // for IE
});
};
});
}());
我有这个 Plunker显示我的代码的样子。还有GitHub Issue .
最佳答案
您需要检查输入值是否存在于列表中的模糊。
为此,请执行以下操作:
添加属性 ng-blur="onBlur($event)"
在输入
并在您的 Controller 中定义以下方法:
$scope.onBlur = function (e) {
$timeout(function () {
var val = $(e.target).val();
if(val && $scope.states.indexOf(val) == -1) {
$(e.target).val("")
}
});
};
关于AngularJS [typeahead] 在 onFocus 上重新打开结果下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38627020/