就像在数据列表HTML标记中一样,即使用户单击建议或按下键导航建议,我也必须能够将焦点保持在输入框中。
我正在尝试创建自己的自动填充字段。就像ng2-controler或mat-autocomplete在材料上一样,但是我无法使用它们,因为我无法在服务器上添加库或模块。
现在,我有一个工作输入框,当它具有焦点时,在其下方显示一个建议列表。当用户按下一个键时,建议将被重新评估。 问题在于,当用户单击建议(带有ng-onclick的标记)时,输入框失去了焦点,因此建议消失了,并且永远不会触发onclick。
<!-- filteredUsers is an array with this kind of values :
filteredUsers = [ {"letter" : "A",
"names" : ["albert@mail.com", "alice@mail.com"],
{"letter" : "P",
"names" : ["philip@mail.com"]}
]
-->
<div>
<div>
<input type="text" ng-focus="c.focus = !c.focus" ng-blur="c.focus = !c.focus" class="form-control" ng-model="c.email">
</div>
<div class="datalist panel-body" ng-if="c.focus && c.filteredUsers.length > 0" style="">
<span class="select2-search" ng-repeat="obj in c.filteredUsers">
{{obj.letter}}
<ul>
<p ng-repeat="email in obj.names">
<a href ng-click="getMyCtrlScope().change(email)">{{email}}</a>
</p>
</ul>
</span>
</div>
</div>
我希望用户在列表中选择建议时输入框不会失去焦点。当然,当用户选择输入框或建议之外的其他对象时,必须失去焦点。
答案 0 :(得分:0)
一种方法是保存具有焦点的元素:
<input ng-model="x" save-focus="lastTarget=$target">
app.directive("saveFocus", function() {
return { link: postLink, };
function postLink(scope, elem, attrs) {
elem.on("focus", function (e) {
scope.$apply(function() {
scope.$eval(attrs.saveFocus, {$target:e.target});
});
});
}
})
然后单击元素将焦点移回:
<button ng-click="x=+x+1" re-focus="lastTarget">
app.directive("reFocus", function() {
return { link: postLink, };
function postLink(scope, elem, attrs) {
elem.on("click", function(e) {
scope.$eval(attrs.reFocus).focus();
})
}
})
angular.module("app",[])
.directive("saveFocus", function() {
return { link: postLink, };
function postLink(scope, elem, attrs) {
elem.on("focus", function (e) {
scope.$apply(function() {
scope.$eval(attrs.saveFocus, {$target:e.target});
});
});
}
})
.directive("reFocus", function() {
return { link: postLink, };
function postLink(scope, elem, attrs) {
elem.on("click", function(e) {
scope.$eval(attrs.reFocus).focus();
})
}
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<input ng-model="x" save-focus="lastTarget=$target">
<br>
<button ng-click="x=+x+1" re-focus="lastTarget">
Increment X
</button>
</body>