我正在尝试在Angularjs中编写自动完成功能。它对我有用,除了点击建议。从控制台日志中,每当我单击建议时,输入元素的ng-blur就会被调用,因为输入元素失去焦点,而从不调用ng-click。有人可以在这里提出解决方案吗?
这是我的代码。
<!DOCTYPE html>
<head>
<title>Autocomplete</title>
<style>.wrapper {display: none;}.wrapper ul {list-style-type: none;}.wrapper li {padding: 5px;line-height: 25px;cursor: pointer;}</style>
<!-- Angular JS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
</head>
<body ng-app="MyApp">
<div ng-controller="SuggestionCtrl">
<form action="/index.html">
<input type="search" name="q" autocomplete="off"
ng-model="q"
ng-focus="showSuggesions()"
ng-blur="hideSuggesions()"
ng-change="getSuggestion()">
<div class="wrapper"
ng-if="hasSuggestions"
ng-style="suggestionStyle">
<ul>
<li ng-repeat="suggestion in suggestions"
ng-click="search(suggestion)">
{{suggestion}}
</li>
</ul>
</div>
</form>
</div>
var app = angular.module("MyApp", []);
app.controller("SuggestionCtrl", function ($scope) {
$scope.suggestions = ["India", "United States", "England", "Australia"];
$scope.showSuggesions = function () {
$scope.suggestionStyle = { display: "block", 'background-color': '#ddd' };
};
$scope.hideSuggesions = function () {
$scope.suggestionsVisible = false;
$scope.suggestionStyle = { display: "none" };
console.log('hideSuggestions called');
};
$scope.hasSuggestions = function(){
return $scope.suggestions.length > 0;
}
$scope.getSuggestion = function () {
// get suggestions from api
};
$scope.search = function (suggestion) {
window.location = window.location + "?q=" + suggestion;
};
});
答案 0 :(得分:0)
click
事件在blur
之后执行-带有建议的列表将隐藏,然后才能单击它。简单的解决方案是使用mousedown
代替click
<input type="search" name="q" autocomplete="off"
ng-model="q"
ng-focus="show=true"
ng-blur="show=false">
<div class="wrapper"
ng-style="suggestionStyle">
<ul ng-show="show">
<li ng-repeat="suggestion in suggestions">
<a ng-mousedown="search(suggestion)">{{suggestion}}</a>
</li>
</ul>